更好的方法是使用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函数并以不同的方式处理结果!