简体   繁体   English

如何将JSON响应存储到JavaScript中

[英]How to store JSON response into JavaScript

I'm trying to store the JSON response in to variable so that I can process it later, i tried with following but getting null, 我正在尝试将JSON响应存储到变量中,以便以后可以处理它。

function go(){
   var jsonObj = getJson(url);
   alert(JSON.stringify(jsonObj));
  }

function getJson(){
    return JSON.parse($.ajax({
        type: 'POST',
        url: 'url',
        dataType: 'json',
        global: false,
        async: false,
        success: function(data){
        return data;
        }
    }).responseText);
}

mean time i can see the JSON content getting printed on my server console. 同时,我可以看到JSON内容正在服务器控制台上打印。

EDIT 编辑

Thannks rid..! 坦克斯摆脱了..! that fixed the issue. 解决了这个问题。 you solution works fine in IE8, but for Chrome and FireFox still getting 'null' in alert pop-up. 您的解决方案在IE8中工作正常,但对于Chrome和FireFox,警报弹出窗口仍然为“空”。 i don't think its browser specific fix..? 我不认为其浏览器特定的修复..?

$.ajax({
        type: 'POST',
        url: 'url',
        dataType: 'json',
        global: false,
        async: false,
        success: function(data){
         // do some stufs or assign data to a var
         window.myVar = data;
        }
   });

Ajax is asynchronous ,so you need to store the response in a variable in the callback. Ajax是异步的,因此您需要将响应存储在回调中的变量中。 in this exemple , window.myVar is a global variable that will contain the response data. 在此示例中,window.myVar是一个全局变量,它将包含响应数据。 You cant access the variable until a response has returned , you'll need to write async code. 在返回响应之前,您无法访问变量,您需要编写异步代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM