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

Ric*_*ler 21 javascript json xmlhttprequest

我正在用JavaScript编写一些代码.在这段代码中我想读一个json文件.该文件将从URL加载.

如何在JavaScript中的对象中获取此JSON文件的包含?

这是我的JSON文件,位于../json/main.json:

{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
Run Code Online (Sandbox Code Playgroud)

我想在我的table.js文件中使用它像这样:

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>');
} 
Run Code Online (Sandbox Code Playgroud)

Dre*_*kes 45

这是一个不需要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();
}
Run Code Online (Sandbox Code Playgroud)

称之为:

loadJSON('my-file.json',
         function(data) { console.log(data); },
         function(xhr) { console.error(xhr); }
);
Run Code Online (Sandbox Code Playgroud)