加载本地JSON文件 [英] Loading local JSON file
本文介绍了加载本地JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试加载本地JSON文件,但它不起作用。这是我的JavaScript代码(使用jQuery:
I'm trying to load a local JSON file but it won't work. Here is my JavaScript code (using jQuery:
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
test.json文件:
The test.json file:
{"a" : "b", "c" : "d"}
没有显示任何内容,Firebug告诉我数据是在Firebug中我可以看到 json.responseText
并且它很好且有效,但是当我复制该行时很奇怪:
Nothing is displayed and Firebug tells me that data is undefined. In Firebug I can see json.responseText
and it is good and valid, but it's strange when I copy the line:
var data = eval("(" +json.responseText + ")");
在Firebug的控制台中,它可以工作,我可以访问数据。
in Firebug's console, it works and I can access data.
任何人都有解决方案吗?
Anyone have a solution?
推荐答案
$ .getJSON
是异步的,所以你应该这样做:
$.getJSON
is asynchronous so you should do:
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
这篇关于加载本地JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文