加载本地 JSON 文件 [英] Loading local JSON file

查看:31
本文介绍了加载本地 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 告诉我 data 是未定义的.在 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.

有人有解决办法吗?

推荐答案

$.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆