将整个json文件作为数组加载到变量中

时间:2012-12-03 00:28:22

标签: javascript jquery arrays json variables

我想获取外部json文件(locations.json)并将内容加载到变量中。然后,我想使用此处提供的信息来使用此变量:http://www.json.org/js.html

我在尝试将外部json加载到变量时遇到了很多麻烦。我已经看了很多这个(load json into variable)页面,但实际上并没有填充变量。稍后显示变量的内容时,它似乎为空。

$("#testContain").html("<p>" + json + "</p>");

使用上一个链接中列出的方法,此发送“未定义”。

我使用的json文件如下所示:

[{"id":"1","locname":"Dunstable Downs","lat":"51.8646","lng":"-0.536957","address":"Chiltern Gateway Centre","address2":"","city":"","state":"England","postal":"","phone":"","web":"http:\/\/www.nationaltrust.org.uk\/main\/w-dunstabledownscountrysidecentrewhipsnadeestate","hours1":"","hours2":"","hours3":""},
{"id":"2","locname":"West Delta Park","lat":"45.5974","lng":"-122.688","address":"N Broadacre St and N Expo Rd, Portland","address2":"","city":"","state":"OR","postal":"","phone":"","web":"http:\/\/en.wikipedia.org\/wiki\/Delta_Park","hours1":"","hours2":"","hours3":""}]

有人有任何建议吗?

1 个答案:

答案 0 :(得分:2)

问题是请求是异步的。您可以根据您链接的问题的接受答案建议进行同步呼叫,但这通常不是一个好主意,因为它会在等待响应时完全冻结浏览器。

变量分配得很好,但是在请求它之后使用它时,你必须确保它在获得响应之后,而不仅仅是在发送请求之后。使用getJSON方法回调中的值是确保您拥有该值的最简单方法:

var my_json;
$.getJSON(my_url, function(json) {
  my_json = json;
  // here you have the value
});
// here you don't have the value, as this happens before the response arrives