Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

javascript - 加载本地JSON文件(Loading local JSON file)

I'm trying to load a local JSON file but it won't work. (我正在尝试加载本地JSON文件,但无法正常工作。) Here is my JavaScript code (using jQuery: (这是我的JavaScript代码(使用jQuery:)

var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);

The test.json file: (test.json文件:)

{"a" : "b", "c" : "d"}

Nothing is displayed and Firebug tells me that data is undefined. (什么都没有显示,Firebug告诉我数据未定义。) In Firebug I can see json.responseText and it is good and valid, but it's strange when I copy the line: (在Firebug中,我可以看到json.responseText ,它很好且有效,但是当我复制该行时很奇怪:)

 var data = eval("(" +json.responseText + ")");

in Firebug's console, it works and I can access data. (在Firebug的控制台中,它可以正常工作,并且我可以访问数据。)

Anyone have a solution? (有人有解决办法吗?)

  ask by Patrick Browne translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$.getJSON is asynchronous so you should do: ($.getJSON是异步的,因此您应该执行以下操作:)

$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...