如何让程序等待ajax结果继续处理?

时间:2011-05-20 18:57:43

标签: jquery ajax callback

我正在进行表单验证。在表单检查功能中,我调用了ajax函数来验证字段。如果ajax的返回数据等于“No”,则该函数应该返回false。但是,它永远不会等待ajax结果返回。我该如何处理这个问题? 我的按钮代码:

jQuery代码:

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;
}

然后我将我的ajax代码修改为

$.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;

我认为这次返回值是在数据发布后执行的,但仍然不起作用。

1 个答案:

答案 0 :(得分:1)

ajax是异步的,所以你必须使用回调。

   $.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
        } 
    });