本文介绍了如何在没有jQuery的情况下在JavaScript中打开JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用JavaScript编写一些代码。在这段代码中我想读一个json文件。此文件将从URL加载。
I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
如何在JavaScript中的对象中获取此JSON文件的包含?
How can I get the contains of this JSON file in an object in JavaScript?
这是我的JSON文件,位于 ../ json / main.json
:
This is for example my JSON file located at ../json/main.json
:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
我想用它在我的 table.js
文件中,如下所示:
and i want to use it in my table.js
file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
推荐答案
这是一个没有做出的例子需要jQuery:
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
将其称为:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
这篇关于如何在没有jQuery的情况下在JavaScript中打开JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!