Javascript - 如何从JSON数组(URL)创建变量?

时间:2015-09-05 22:52:26

标签: javascript json callback

我有一个JSON数组,如:

[  
  {  
     "location":"New York",
     "company":"XYZ LTD",
     "status":"Active"
  },
  ... etc
]

我使用以下函数从URL返回此数组:

var getJSON = function(url, successHandler, errorHandler) {
  var xhr = typeof XMLHttpRequest != 'undefined'
    ? new XMLHttpRequest()
    : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('get', url, true);
  xhr.onreadystatechange = function() {
    var status;
    var data;
    // https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
    if (xhr.readyState == 4) { // `DONE`
      status = xhr.status;
      if (status == 200) {
        data = JSON.parse(xhr.responseText);
        successHandler && successHandler(data);
      } else {
        errorHandler && errorHandler(status);
      }
    }
  };
  xhr.send();
};

我们使用这样的功能:

getJSON('http://example.com/json.php', function(data) { 
  alert('Data was collected successfully.');
}, 
function(status) { 
  alert('Something went wrong while retrieving the location data.');
});

好的,这很有效,并且收集了数据。我对Javascript很新,我不确定如何将在Javascript中作为变量收集的数据存储起来。

我试过了:

getJSON('http://example.com/json.php', function(data) { 
  var myData = data;
}, 
...end

var myData = getJSON('http://example.com/json.php', function(data) { 
  return data;
}, 
...end

但此时,如果我这样做:

console.log(myData);

然后我得到undefined。但如果我这样做:

var myData = getJSON('http://example.com/json.php', function(data) { 
  console.log(data);
}, 
...end

我回来[Object,Object]这是我的数据!

那么如何从successHandler中获取数据并存储为变量?

1 个答案:

答案 0 :(得分:1)

var myData;
getJSON('http://example.com/json.php', function(data) { 
  myData = data;
}, ...

声明函数范围之外的变量。这就是诀窍。

最好的问候。

更新:请注意,ajax是asyncron。如果您在getJSON调用下使控制台输出正确,它将无法正常工作,因为尚未收到数据。