2013-04-05 108 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(); },