我想存储来自ajax调用的响应结果。这是因为ajax是几个函数用来从API提取信息的主要API调用。
我在我的应用程序中多次调用callAPI函数超过8次。 当然,我可以将函数callAPI复制8次以正确获取信息,但这不是很不错的编码方式。
var result = callAPI("GET",url,'');
$('#status').val(result.success);
$('#output').val(result);
function callAPI(method_input, url_input, body_input){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
});
}
我尝试使用以下方式存储返回值 var result = ajax(value); 但结果为空
有什么方法可以将函数的返回值存储到变量中?
答案 0 :(得分:1)
您需要'async': false
,所以:
var result = $.ajax({
url: "https://api.github.com/users",
'async': false,
type: 'GET'
})
.done(function(data,status) {
console.log("success");
})
.fail(function(data,status) {
console.log("error");
});
console.log("result: " + result.responseText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 1 :(得分:0)
一些注意事项:
JSON.stringify()
来解析您的API可能返回的JSON字符串,而不是JSON.parse()
。$.ajax
选项dataType
自动将JSON字符串解析为对象。$.ajax()
返回一个promise,该promise可以链接以添加所需的尽可能多的回调。一个更优雅的解决方案是从函数中返回诺言并链接您的回调。例如:
function callAPI(method_input, url_input, body_input) {
var urli = url_input;
var datai = body_input;
var method = method_input;
return $.ajax({
url: urli,
// Automatically parses JSON response
dataType: 'json',
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("some header", "some value");
},
type: method,
data: datai,
})
.done(function(data, status) {
console.log("success");
console.log(data);
})
.fail(function(data, status) {
console.log("error");
console.log(data);
});
}
callAPI('GET', '').then(function(result){
// Do something with my API result
});
如果您计划一次发出所有请求,则可以使用此解决方案考虑使用$.when()
将所有请求汇总为一个承诺。例如:
$.when(
callAPI('GET', ''),
callAPI('GET', 'second'),
callAPI('GET', 'third')
).then(function(firstResult, secondResult, thirdResult){
// Do stuff with the result of all three requests
});