gpt4 book ai didi

javascript - 如何将 ajax 请求包装到函数中?

转载 作者:行者123 更新时间:2023-12-01 03:02:21 25 4
gpt4 key购买 nike

这是我的代码:

function ajaxRequest(value, path, website){
window[website] = $.ajax({
url : path,
type : 'GET',
data: { "name": value,
"_token": $('meta[name="_token"]').attr('content')
},

beforeSend: function(){
if(window[website] != null) {
window[website].abort();
}
},
success: function (people) {
return [status, people];
},

error: function (jqXHR, textStatus, errorThrown) {
return [status, textStatus];

},

timeout: 15000

});

}

如您所见,它是一个发送ajax请求的函数。我这样调用它:

var res = ajaxRequest('Jack', 'search/twitter', 'twitter');
console.log(res);

它返回:

enter image description here

为什么我在控制台中看不到结果?请注意,如果我发送该 ajax 使其功能失效,我可以在控制台中看到结果。 (结果是一个数据数组)

如何解决这个问题?

最佳答案

function ajaxRequest(value, path, website){

return new Promise(function (resolve, reject) {
window[website] = $.ajax({
url : path,
type : 'GET',
data: { "name": value,
"_token": $('meta[name="_token"]').attr('content')
},

beforeSend: function(){
if(window[website] != null) {
window[website].abort();
}
},
success: function (people) {
resolve([status, people]);
},

error: function (jqXHR, textStatus, errorThrown) {
reject([status, textStatus]);

},

timeout: 15000

});
});
}

然后这样做,得到结果:

ajaxRequest('Jack', 'search/twitter', 'twitter').then(function(res) { console.log(res)}, function(err){console.log(err)})`;

关于javascript - 如何将 ajax 请求包装到函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46378612/

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