Heylow所有人!
我有ajax()
这样的电话:
$.ajax({
type: "post",
url: "whatever.php",
data: {
theData: "moo moo"
},
success: function(data) {
console.log(data);
}
});
是否可以将其包含在自定义函数中,但保留回调?
类似的东西:
function customAjax(u, d, theCallbackStuff) {
$.ajax({
type: "post",
url: u,
data: d,
success: function(data) {
//RUN theCallbackStuff
}
});
}
theCallbackStuff
将类似于:
var m = 1;
var n = 2;
alert(m + n + data);
答案 0 :(得分:10)
编辑:
最近有一个upvote,我觉得有必要声明我不再这样做了。 $.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);
});
答案 1 :(得分:5)
function customAjax(u, d, theCallbackStuff) {
$.ajax({
type: "post",
url: u,
data: d,
success: theCallbackStuff
});
}
customAjax(url, data, function(data){
//do something
});
答案 2 :(得分:1)
在这个注释中,您可以将一个完整的函数作为回调函数传递给它:
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);
}
}
});
}
// Then call it as follows:
function initiator() {
customRequest( '/url/to/post', 'param1=val', function() { alert( 'complete' ); })
}
简单地将它作为匿名函数传递也会起作用..只是为了显示:)