开发者

How to process results from a jQuery ajax post

开发者 https://www.devze.com 2022-12-16 20:59 出处:网络
I am making a jQuery ajax post in a javascript function used by a asp:CustomValidator control.The web method returns a boolean.How do I convert the result make the validation script function correctly

I am making a jQuery ajax post in a javascript function used by a asp:CustomValidator control. The web method returns a boolean. How do I convert the result make the validation script function correctly.

Client side code

<script language="javascript" type="text/javascript">
function ValidateInput(source, args) {
    if($('#开发者_高级运维MyTxtBox').val().length > 0) {
        var result;
        var webMethod = 'http://domain/webservice.asmx/ValidateInput';
        var parameters = "{'input':'" + $('#MyTxtBox').val() + "'}";

        $.ajax({
            type: "POST",
            url: webMethod,
            data: parameters,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {            
                args.IsValid = msg.d;
            }
         });
    }
    else {
        args.IsValid = false;
    }
}
</script>
<asp:TextBox ID="MyTxtBox" runat="server" />
<asp:CustomValidator ID="cvCreditCardNumber" runat="server" ClientValidationFunction="ValidateCCNumber" Display="Dynamic" 
ErrorMessage="&nbsp;Please enter valid input." />

Web service code

[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public bool ValidateInput(string input)
{
    if(input.Equal("jQuery is awesome!"))
        return true;
    else
        return false;
}


Well I don't think this is going to work in the usual fashion. The AJAX request is asynchronous, and since there is only one UI thread you can't block to wait on it. The validation function provided to ASP.NET must be synchronous.

You can hack it up to work, maybe, if you can delay when validation occurs and start the AJAX request early. But in this case, I'd say just use server-side validation as what you have as client-side validation is hitting the server anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消