gpt4 book ai didi

javascript - jQuery promise 函数

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

我正在尝试创建全局 ajax 处理程序。首先让我向您展示该功能

    var data = {
test : 1
}
$.when( $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
})
).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});

这样就可以了。和输出

首先是我

然后是我

但是我希望这个ajax成为一个函数这就是我正在努力实现的方法。

    var data = {
test : 1
}
$.when(globalAjax(data)).then(function( data, textStatus, jqXHR ) {
console.log('then me')
});
<小时/>
    function globalAjax(data) {
$.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
})

}

这样控制台会输出然后是我,然后是首先是我

如何要求在函数内等待ajax?

最佳答案

您需要在 globalAjax 中返回一个 promise :

function globalAjax(data) {
return $.ajax({
type: 'POST',
url: ajaxurl,
data : data,
dataType: "json",
success: function(data) {
console.log('first me')
}
});
}

并且您不需要使用 $.when 函数:

globalAjax(data).then(function(data, ...) { ... });

$.when主要是等待两个或多个deferreds或promise完成。

关于javascript - jQuery promise 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22459652/

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