Jquery - 将 Ajax JSON 响应存储为变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4763918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:54:19  来源:igfitidea点击:

Jquery - Store Ajax jSON response as variable

jqueryajaxjsonvariables

提问by Sebastien

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 variablebut my variable beerremains undefined outside the $.getJSONand $.ajaxfunctions (I tried both).

我试图将 ajax 请求的结果设置在一个我可以在该请求之外访问的变量中。我试过这个JQuery - 将 ajax 响应存储到全局变量中,但我的变量beer$.getJSON$.ajax函数之外仍未定义(我都试过)。

Here is my code and where I am able to see the results from the console.log(beer).

这是我的代码,我可以在这里看到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

回答by chprpipr

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:

这是一个异步请求,因此它会被触发,但是您的脚本在继续之前不会等待响应。如果您需要等待 ajax 请求完成,请尝试以下操作:

var beer;
$.getJSON(jsonUrl,function(json){
    beer = json;   
    checkDrink();                
});         

function checkDrink() {
    console.log(beer);
}   

回答by userlond

Suggest the code below:

建议使用以下代码:

var beer = $.ajax({
    url: jsonUrl,
    async: false,
    dataType: 'json'
}).responseJSON;

The key moments are:

关键时刻是:

  1. set asyncto false, to return result as variable, not call success callback asynchronious
  2. set dataTypeto json to parse server response string as json
  1. 设置async为false,将结果作为变量返回,而不是异步调用成功回调
  2. 设置dataType为 json 以将服务器响应字符串解析为 json

回答by Jaime

The problem is that you're trying to access the data before it actually comes back from the server, the 'success' function is actually a callback that gets called when the ajax call finishes successfully. The $.ajax (or $.get) functions return inmediatly...

问题是您试图在数据实际从服务器返回之前访问数据,“成功”函数实际上是一个回调,当 ajax 调用成功完成时会调用它。$.ajax(或 $.get)函数立即返回......

You would need to somehow signal to the interested functions that you got the data into the 'beer' var inside your success callback

您需要以某种方式向感兴趣的函数发出信号,表明您已将数据放入成功回调中的“啤酒”变量中