我试图加载一个本地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的控制台中,它可以工作,我可以访问数据。
有人有办法吗?
在一个更现代的方式,你现在可以使用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
美元。getJSON只适用于我在Chrome 105.0.5195.125使用等待,这是一个脚本类型的模块。
<script type="module">
const myObject = await $.getJSON('./myObject.json');
console.log('myObject: ' + myObject);
</script>
无须等待,我看到:
Uncaught TypeError: myObject is not iterable
当解析myObject时。
没有type="module"我看到:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules