編輯:
得到了這個最近給予好評,我覺得有必要指出,我不會再這樣做了。 $.ajax
返回promise
,這樣您就可以直接使用承諾,以更加一致和可靠的方式完成我剛纔所做的工作。
function customRequest(u,d) {
var promise = $.ajax({
type: 'post',
data: d,
url: u
})
.done(function (responseData, status, xhr) {
// preconfigured logic for success
})
.fail(function (xhr, status, err) {
//predetermined logic for unsuccessful request
});
return promise;
}
然後使用看起來像:
// using `done` which will add the callback to the stack
// to be run when the promise is resolved
customRequest('whatever.php', {'somekey': 'somevalue'}).done(function (data) {
var n = 1,
m = 2;
alert(m + n + data);
});
// using fail which will add the callback to the stack
// to be run when the promise is rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).fail(function (xhr, status, err) {
console.log(status, err);
});
// using then which will add callabcks to the
// success AND failure stacks respectively when
// the request is resolved/rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).then(
function (data) {
var n = 1,
m = 2;
alert(m + n + data);
},
function (xhr, status, err) {
console.log(status, err);
});
肯定我做這一切的時候。您可以執行實際成功callack內的回調或您可以指定回調的成功回調:
function customRequest(u,d,callback) {
$.ajax({
type: "post",
url: u,
data:d,
success: function(data) {
console.log(data); // predefined logic if any
if(typeof callback == 'function') {
callback(data);
}
}
});
}
用法看起來是這樣的:
customRequest('whatever.php', {'somekey': 'somevalue'}, function (data) {
var n = 1,
m = 2;
alert(m + n + data);
});
你試過了嗎?我想這將是可能的 –
因此,我可以在'theCallbackStuff'中保存一個完整的函數嗎? –
我現在正在工作,所以我不能嘗試它 - 我在腦海中理論化;) –