How to let program wait for ajax result to continu

2019-09-04 13:37发布

I'm doing form validation. In the form check function, I called an ajax function to verify a field. if the return data of ajax equals "No", this function supposed to return false. However, it never wait for the ajax result return. How should I handle this issue? my button code:

jQuery code:

function Checkform() {
        var result = true;
        $('input:password').each(function() {
            if ($(this).val() == "") {
                $(this).focus();
                $(this).addClass('HighlightBorder');
                alert("Please set password.");
                result = false;
                return false;
            }
        });
        if (!result)
            return false;
......
       $.post(rootPath + "/AjaxPages/SearchAddress.aspx", { "street": street, "city": city, "state": state, "zip": zip, "type": "DPV" }, function(data) {
            if (data == "No") {
                alert("Invalid company address, did you type in a wrong address?");
                result=false;
            } 
        });
        return result;
}

Then I modified my ajax code to

$.post(rootPath + "/AjaxPages/SearchAddress.aspx", { "street": street, "city": city, "state": state, "zip": zip, "type": "DPV" }, function(data) {
            if (data == "No") {
                alert("Invalid company address, did you type in a wrong address?");
                return false;
            } else
                return true;

I think this time the return value is performed after the data comes out, but still, it doesn't work.

1条回答
等我变得足够好
2楼-- · 2019-09-04 14:02

ajax is asynchronous, so you have to use callbacks.

   $.post(rootPath + "/AjaxPages/SearchAddress.aspx", { "street": street, "city": city, "state": state, "zip": zip, "type": "DPV" }, function(data) {
        if (data == "No") {
            alert("Invalid company address, did you type in a wrong address?");
            some_callback_function();//callback
        } 
    });
查看更多
登录 后发表回答