How can I open a JSON file in JavaScript without jQuery?

前端 未结 4 608
清歌不尽
清歌不尽 2020-11-27 15:20

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.

How can I get the contains of this JSON file in

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 15:31

    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();
    }
    

    Call it as:

    loadJSON('my-file.json',
             function(data) { console.log(data); },
             function(xhr) { console.error(xhr); }
    );
    

提交回复
热议问题