jQuery-将Ajax jSON响应存储为变量 [英] Jquery - Store Ajax jSON response as variable
问题描述
我正在尝试获取ajax请求的结果,以将其设置为可以在该请求之外访问的变量.我已经尝试过 JQuery-将ajax响应存储到全局变量中,但是我的变量beer
在$.getJSON
和$.ajax
函数之外仍然未定义(我都尝试过).
I'm trying to get the result of an ajax request to set in a variable which I can access outside that request. I've tried this JQuery - Storing ajax response into global variable but my variable beer
remains undefined outside the $.getJSON
and $.ajax
functions (I tried both).
这是我的代码,可以在其中查看console.log(beer)
的结果.
Here is my code and where I am able to see the results from the console.log(beer)
.
var beer;
$.getJSON(jsonUrl, function (json) {
beer = json;
console.log(beer); // returns beer
});
console.log(beer); // returns undefined
var beer = (function () {
var result;
$.ajax({
url: jsonUrl,
success: function (data) {
result = data;
console.log(beer); // returns beer
}
});
console.log(result); // returns undefined
if (result) return result;
})();
console.log(beer); // returns undefined
推荐答案
这是一个异步请求,因此它会被触发,但是您的脚本不会等待响应再继续运行.如果您需要等待ajax请求完成,请尝试以下操作:
That's an asynchronous request, so it gets fired off, but your script doesn't wait around for a response before it moves on. If you need to wait on a ajax request to finish, try something like this:
var beer;
$.getJSON(jsonUrl,function(json){
beer = json;
checkDrink();
});
function checkDrink() {
console.log(beer);
}
这篇关于jQuery-将Ajax jSON响应存储为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!