我试图加载一个本地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的控制台中,它可以工作,我可以访问数据。
有人有办法吗?
如何使用XMLHttpRequest加载本地json文件
ES5版本
// required use of an anonymous callback,
// as .open() will NOT return a value but simply returns undefined in asynchronous mode!
function loadJSON(callback) {
var xObj = new XMLHttpRequest();
xObj.overrideMimeType("application/json");
xObj.open('GET', './data.json', true);
// 1. replace './data.json' with the local path of your file
xObj.onreadystatechange = function() {
if (xObj.readyState === 4 && xObj.status === 200) {
// 2. call your callback function
callback(xObj.responseText);
}
};
xObj.send(null);
}
function init() {
loadJSON(function(response) {
// 3. parse JSON string into JSON Object
console.log('response =', response);
var json = JSON.parse(response);
console.log('your local JSON =', JSON.stringify(json, null, 4));
// 4. render to your page
const app = document.querySelector('#app');
app.innerHTML = '<pre>' + JSON.stringify(json, null, 4) + '</pre>';
});
}
init();
<section id="app">
loading...
</section>
ES6版本
// required use of an anonymous callback,
// as .open() will NOT return a value but simply returns undefined in asynchronous mode!
const loadJSON = (callback) => {
const xObj = new XMLHttpRequest();
xObj.overrideMimeType("application/json");
// 1. replace './data.json' with the local path of your file
xObj.open('GET', './data.json', true);
xObj.onreadystatechange = () => {
if (xObj.readyState === 4 && xObj.status === 200) {
// 2. call your callback function
callback(xObj.responseText);
}
};
xObj.send(null);
}
const init = () => {
loadJSON((response) => {
// 3. parse JSON string into JSON Object
console.log('response =', response);
const json = JSON.parse(response);
console.log('your local JSON =', JSON.stringify(json, null, 4));
// 4. render to your page
const app = document.querySelector('#app');
app.innerHTML = `<pre>${JSON.stringify(json, null, 4)}</pre>`;
});
}
init();
<section id="app">
loading...
</section>
在线演示
https://cdn.xgqfrms.xyz/ajax/XMLHttpRequest/index.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
在尝试(不成功)加载本地json文件时发现此线程。这个方法对我很有效。
function load_json(src) {
var head = document.getElementsByTagName('head')[0];
//use class, as we can't reference by id
var element = head.getElementsByClassName("json")[0];
try {
element.parentNode.removeChild(element);
} catch (e) {
//
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
script.className = "json";
script.async = false;
head.appendChild(script);
//call the postload function after a slight delay to allow the json to load
window.setTimeout(postloadfunction, 100)
}
... And的用法是这样的…
load_json("test2.html.js")
...这是<head>…
<head>
<script type="text/javascript" src="test.html.js" class="json"></script>
</head>