gpt4 book ai didi

jquery ajax : when to use callback hooks vs settings functions?

转载 作者:行者123 更新时间:2023-11-30 23:43:28 24 4
gpt4 key购买 nike

据我所知 the documentation ,有两种不同的方法来处理 $.ajax() 调用的响应。

1) 将函数传递到 $.ajax() 的设置对象中:

$.ajax({
success: function(){ ... },
error: function(){ ... }
});

2) 作为可链接的“回调 Hook ”

$.ajax({...})
.done(function(){ ... })
.fail(function(){ ... })

这两种方法之间的重要区别是什么?我什么时候应该选择其中一种?

最佳答案

如果您直接在调用中附加该函数,则用法没有太大区别。当您希望在其他地方使用回调函数时,就会出现差异。

将回调函数发送到方法中:

function callForMe(callback) {
$.ajax({
url: '...',
success: callback
});
}

callForMe(function(data){
// handle the response
});

从方法返回 promise ,稍后等待响应:

function callFormMe() {
return $.ajax({
url: '...'
});
}

var promise = callForMe();
// later on:
promise.done(function(data){
// handle the response
});

关于jquery ajax : when to use callback hooks vs settings functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com