我知道这个问题可能已经有一百万次了,但是在我的生活中,我无法得到任何工作。在转移到其他代码之前等待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