小编典典

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

json

我正在用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'}]}

我想像这样在我的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>');
}

阅读 299

收藏
2020-07-27

共1个答案

小编典典

这是一个不需要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); }
);
2020-07-27