如何在没有 jQuery 的情况下在 JavaScript 中打开 JSON 文件?

2022-01-15 00:00:00 json xmlhttprequest javascript

我正在用 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); }
);

相关文章