我正在使用jquery ajax进行保存,例如
$.ajax({
type: "POST",
url: "/service/save.php",
data: dataString,
cache: false,
async: true, // false is deprecated, do not use
success: function(result){
var split = result.split("##");
if(split[0] == "exception") {
alert(split[1]);
ajaxStatus = 0;
} else {
ajaxStatus = 1;
}
}
});
我的问题是我需要在当前线程上等待结果才能继续。
我尝试过使用async:false,这有效,但不推荐使用,我需要另外一种方法。
此外,我尝试使用计时器和回调,如
ajaxWaitResponse(function() {
return ajaxStatus
});
function ajaxWaitResponse(callback) {
if (ajaxStatus > -1) {
alert("SUCCESS");
// we have a response
callback();
} else {
// wait again
setTimeout(function() {ajaxWaitResponse(callback)}, 1000); // just a 1 second delay
}
}
但主线程上的执行继续通过回调。 请注意,我需要等待当前的线程。 我需要暂停当前线程的执行,而不会阻止执行ajax线程。
提前致谢
答案 0 :(得分:0)
更好的方法是使用jQuery Promises。这样的事情可以奏效:
var ajaxRequest = function () {
var deferred = $.Deferred();
$.ajax({
type: "POST",
url: "/service/save.php",
data: dataString,
success: function (result) {
// This will fire the done function
deferred.resolve(result);
},
error: function (xhr, status, errorThrown) {
// This will fire the fail function
deferred.reject(xhr, status, errorThrown);
}
});
return deferred.promise();
};
var somefunction = function () {
// This will return a promise
var getSomeData = ajaxRequest();
// The appropriate function will be called based on if the promise is resolved or rejected through the success and error functions in the AJAX request
getSomeData.then(
// Done response
function (result) {
alert("Success!");
// Enter logic here to handle the data which you have waited for
},
// Fail response
function (xhr, status, errorThrown) {
// Handle errors here...
}
);
};
somefunction();
如果你愿意,这个方法还允许你重用ajaxRequest函数并以不同的方式处理结果!