gpt4 book ai didi

javascript - Ajax 在返回值之前等待响应

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

基本上,我在让我的程序等待 AJAX 请求完成时遇到问题。在下面的示例代码中,除了调用 getFriends() 的 test() 函数中未定义之外,我似乎无法获得任何返回值。我可以在 ajax 调用中将 async 设置为 false 使其正常工作,但由于这已被弃用,我想避免使用此解决方案。

我尝试使用 deferred 来解决这个问题,并且在堆栈溢出中找到了很多其他选项,但没有运气,所以我得出的结论是,我可能使用 deferred 错误或(不太可能) deferred 不是一个选项在这里,所以我希望这个网站上的一位有才华的人可以帮助我!

查看下面我的代码;它是我正在运行的简单版本。提前致谢!

//function that shows how the function with issue should be called/used
function test(){
var result = getFriends(127, 1); //this is getting a result returned before ajax is done so the result is undefined

//do stuff with result data
console.log(result);
}


//function that creates a data object and calls my custom ajax function
function getFriends(user_id, page_no){

//create data object containing given parameters and a data type parameter
var data = {
page_no: page_no,
profile_id: user_id,
request_type: 'get_friends'
};

//call friendAjax to get users friends
var response = friendAjax(data, 'kv_people_feed');
return response;
}



//Used for all friend related ajax requests. Accepts a data object to be sent as parameters and otional url.
function friendAjax(data, url){
url = typeof url !== 'undefined' ? url : 'friendsLibrary'; //allows optional url param
$.ajax({
// async: false,
url: Config.home + '/' + url + '/', //dynamic url
data: data,
dataType: 'jsonp',
success: function(response){
console.log(response);
return response;
}
});
}

最佳答案

问题是 $.ajax 是异步执行的。 friendAjax() 在 ajax 调用之前返回。此外,您获得的返回结果是在匿名函数中返回成功的结果。

您可以添加对friendAjax的回调来解决此问题。

function friendAjax(data, url, callback){
url = typeof url !== 'undefined' ? url : 'friendsLibrary'; //allows optional url param
$.ajax({
// async: false,
url: Config.home + '/' + url + '/', //dynamic url
data: data,
dataType: 'jsonp',
success: function(response){
console.log(response);
callback(response);
}
});
}

然后当你调用它时:

friendAjax({}, "http://wherever.com", function(data){
// Data will be defined here.
console.log(data);
}

关于javascript - Ajax 在返回值之前等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058093/

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