0

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

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

$("#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":""}]

有人有什么建议吗?

4

1 回答 1

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
于 2012-12-03T00:38:42.247 回答