我试图加载一个本地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的控制台中,它可以工作,我可以访问数据。
有人有办法吗?
在TypeScript中,你可以使用import来加载本地JSON文件。例如,加载一个font.json:
import * as fontJson from '../../public/fonts/font_name.json';
这需要tsconfig标志——resolveJsonModule:
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"resolveJsonModule": true,
"esModuleInterop": true
}
}
有关更多信息,请参阅typescript的发布说明:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html
在一个更现代的方式,你现在可以使用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