我知道這個問題可能已經有一百萬次了,但是在我的生活中,我無法得到任何工作。在轉移到其他代碼之前等待Async ajax完成?
我有一個UI嚮導控件,在「changed」事件驗證模型。如果模型無效,則不允許用戶在嚮導中向前移動。我已經厭倦了在jquery中使用$ .when()。done()功能,但是在確保模型有效之前,我的代碼仍然通過。調用異步ajax請求的原因是我不希望UI鎖定,所以我可以顯示某種進度指示器。我已將async屬性設置爲false,但我的UI指示符永遠不會顯示。這裏是我的代碼是做一個例子:
//the change event that is called when the user clicks 'next' on the wizard:
wizard.on('change', function (e, data) {
var isValid = $.validate({
"Model": [The_UI_MODEL],
"Url": [URL_To_Server_Validation],
"Async": true, //tells ajax request to send as async
});
//Tells the wizard not to move 'next' if the request comes back as not valid
if (data.direction === 'next' && !isValid) {
e.preventDefault();
}
}
//我用$ .extend方法jQuery來創建將驗證所有模型在我的系統的功能。
validate: function(options) {
//Clear any previous validation errors
$.clearValidations();
var data = $.postJson(options);
//the result is getting returned before the $.postJson(options) finishes
return data.Success;
}
//我創造了我自己的方法,它擴展了$就法,所以我可以請求後/前做其它事情:
postJson: function(options){
...other code for my application
//This is where I want the ajax request to happen and once done return the data coming back
//This is what I have tried, but it is not doing what I thought.
$.when(function(){
return $.ajax({
url: options.Url,
type: 'POST',
cache: false,
async: options.Async,
timeout: options.Timeout,
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(options.Model),
error: function(xhr, status, error) {
...do stuff if ajax errors out
},
success: function (data) {
},
});
}).done(function(response){
//looks like i get back the responseText of the request. which is fine, but other posts i have read stated i should be getting back the request itself
...other UI stuff
return response;
})
}
編寫一個函數,執行你的操作,並在成功'success:function(data){...}'中調用該函數... – KarelG
@KarelG,change事件首先觸發,然後驗證。由於ajax請求是異步的,所以立即調用$ .validate函數。 'var isValid'始終爲false – DDiVita