2013-04-05 52 views
-1

我有这样的代码..jQuery的AJAX延迟对象没有返回值

if (!checkIfCustomerIsValid(event)) { 
     event.preventDefault(); 
     return false; 
    } 
else { 
    AddCustomer(); 
} 

function checkIfCustomerIsValid(event) { 
    if ($('#txtCName').val() == '') { 
     alert('Please enter a valid value for customer name!'); 
     return false; 
    } 
    if ($('#txtCAddress').val() == '') { 
     alert('Please enter a valid value for customer address!'); 
     return false; 
    } 

} 

它退回罚款,直到这时,我增加了一个新的检查和它不返回任何东西。

function checkIfCustomerIsValid(event) { 

    // code that was already there, the name and address check 

    var _mobNo; 
    if ($('#txtMobile').val() == '') return false; 

    var _unq = $.ajax({ 
     url: '../Autocomplete.asmx/IsMobileUnique', 
     type: 'GET', 
     contentType: 'application/json; charset=utf8', 
     dataType: 'JSON', 
     data: "mobileNo='" + $('#txtMobile').val() + "'", 
     async: false, 
     timeout: 2000, 
     success: function (res) { if (res.d) return false; else return true; }, 
     error: function (res) { alert('some error occurred when checking mobile no'); } 
    }),chained = _unq.then(function (data) { if (data.d == false) { alert('mobile no already exists!'); $('#txtMobile').focus(); return false; } return true; }); 

} 

如果手机号码是不是唯一的警报显示精细,手机无不是唯一的,但是当它唯一的代码不会进入AddCustomer(在其他部分)???它不是真的吗?为什么不进入AddCustomer ???

+0

的[变量不从AJAX函数返回]可能重复(http://stackoverflow.com/questions/12475269/variable-doesnt-get-返回从ajax函数) – 2013-04-05 06:02:12

+0

可能重复的[如何返回来自AJAX调用的响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an -ajax-call) – 2014-02-27 13:08:29

回答

0

通过您的新测试,checkIfCustomerIsValid是异步的。即使延期,也无法直接返回远程呼叫的结果。

最简单的方法是将回调传递给checkIfCustomerIsValid函数或从函数返回承诺。在混合同步和异步测试时,最好的做法是将回调传递给checkIfCustomerIsValid

+0

我已经设置'async:false',那它又是如何异步? – Razort4x 2013-04-05 06:02:53

+0

切勿使用'async':它会阻止用户界面。 – 2013-04-05 06:03:29

+0

我知道,但我只是指出你说我已经设置'async:false',所以它现在不应该是异步的? – Razort4x 2013-04-05 06:04:37

0

你说的没错,checkIfCustomerIsValid不会返回true。这是因为你试图从匿名函数返回true(即在ajax请求后回调)。当您从

chained = _unq.then(function (data) { if (data.d == false) { alert('mobile no already exists!'); $('#txtMobile').focus(); return false; } return true; }); 

返回true,你只是从匿名函数返回时,不是从checkIfCustomerIsValid。解决这个问题并不是完全直截了当,而且是异步调用性质造成的一个问题。最常见的解决方案是将回调传递给异步调用。这是一个实现这一点的小提琴。

http://jsfiddle.net/p3PAs/

0

阿贾克斯是异步的,不会阻止,因此,返回值是最有可能的不确定的。您可以修改代码以类似于下面的东西:

success: function (res) { if (res.d) callRoutineToAddCustomer(); },