且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-03 08:47:09

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