gpt4 book ai didi

jquery - 获取 $.ajax 响应

转载 作者:行者123 更新时间:2023-12-01 08:29:05 24 4
gpt4 key购买 nike

function Profiles() { };

Profiles.prototype.test = function() {
var opt = {
url: __profileurl__+'getall/', type: 'get', dataType:'json',
success:function(response){
return response;
}
};
$.ajax(opt);
};

var profile = new Profiles();

var r = profile.test();

//返回未定义...预期输出应该是请求的响应。

最佳答案

可以使用异步请求来做到这一点,但这通常是坏事

像下面这样的东西应该返回数据。

function Profiles() { };

Profiles.prototype.test = function() {
var returnedResponse;
var opt = {
async: false,
url: __profileurl__+'getall/', type: 'get', dataType:'json',
success:function(response){
returnedResponse = response;
}
};
$.ajax(opt);
return returnedResponse;
};
<小时/>

但是

除非您确实需要能够立即使用测试的返回值,否则将回调传递到测试中会更好。类似的东西

Profiles.prototype.test = function(callback) {
var opt = {
url: __profileurl__+'getall/', type: 'get', dataType:'json',
success:function(response){
callback(response);
}
};
$.ajax(opt);
};

var profile = new Profiles();
profile.test(function(data) {
// do something with the data
});

关于jquery - 获取 $.ajax 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1005942/

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