900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > jquery定义ajax函数吗 jQuery AJAX自定义函数和自定义回调?

jquery定义ajax函数吗 jQuery AJAX自定义函数和自定义回调?

时间:2020-08-05 22:54:04

相关推荐

jquery定义ajax函数吗 jQuery AJAX自定义函数和自定义回调?

小编典典

编辑:

最近对此表示赞同,我不得不说我不再这样做。$.ajax返回a,promise因此您可以直接使用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);

});

-07-26

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。