我试图加载一个本地JSON文件,但它不会工作。下面是我的JavaScript代码(使用jQuery):
var json = $.getJSON("test.json");
var data = eval("(" +json.responseText + ")");
document.write(data["a"]);
测试。json文件:
{"a" : "b", "c" : "d"}
什么也没有显示,Firebug告诉我数据是未定义的。在Firebug中我可以看到json。responseText和它是好的和有效的,但它是奇怪的,当我复制一行:
var data = eval("(" +json.responseText + ")");
在Firebug的控制台中,它可以工作,我可以访问数据。
有人有办法吗?
你可以把json放在javascript文件中。这可以使用jQuery的getScript()函数在本地加载(甚至在Chrome中)。
图- 01. - js文件:
var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'
main.js
$.getScript('map-01.js')
.done(function (script, textStatus) {
var map = JSON.parse(json); //json is declared in the js file
console.log("world width: " + map.worldWidth);
drawMap(map);
})
.fail(function (jqxhr, settings, exception) {
console.log("error loading map: " + exception);
});
输出:
world width: 500
注意,json变量是在js文件中声明和赋值的。
你可以把json放在javascript文件中。这可以使用jQuery的getScript()函数在本地加载(甚至在Chrome中)。
图- 01. - js文件:
var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'
main.js
$.getScript('map-01.js')
.done(function (script, textStatus) {
var map = JSON.parse(json); //json is declared in the js file
console.log("world width: " + map.worldWidth);
drawMap(map);
})
.fail(function (jqxhr, settings, exception) {
console.log("error loading map: " + exception);
});
输出:
world width: 500
注意,json变量是在js文件中声明和赋值的。
在一个更现代的方式,你现在可以使用Fetch API:
fetch("test.json")
.then(response => response.json())
.then(json => console.log(json));
所有现代浏览器都支持Fetch API。(Internet Explorer没有,但Edge有!)
或者使用async/await
async function printJSON() {
const response = await fetch("test.json");
const json = await response.json();
console.log(json);
}
来源:
使用取回
正在执行的取回
我能用…吗?
如何使用Fetch与async/await