Loading local JSON file

前端 未结 23 1580
悲哀的现实
悲哀的现实 2020-11-22 01:28

I\'m trying to load a local JSON file but it won\'t work. Here is my JavaScript code (using jQuery):

var json = $.getJSON("test.json");
var data = e         


        
23条回答
  •  隐瞒了意图╮
    2020-11-22 01:53

    ES5 version

    function loadJSON(callback) {
        var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', 'my_data.json', true);
        // Replace 'my_data' with the path to your file
        xobj.onreadystatechange = function() {
            if (xobj.readyState === 4 && xobj.status === 200) {
                // Required use of an anonymous callback 
                // as .open() will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
            }
        };
        xobj.send(null);
    }
    
    function init() {
        loadJSON(function(response) {
            // Parse JSON string into object
            var actual_JSON = JSON.parse(response);
        });
    }
    

    ES6 version

    const loadJSON = (callback) => {
        let xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
        xobj.open('GET', 'my_data.json', true);
        // Replace 'my_data' with the path to your file
        xobj.onreadystatechange = () => {
            if (xobj.readyState === 4 && xobj.status === 200) {
                // Required use of an anonymous callback 
                // as .open() will NOT return a value but simply returns undefined in asynchronous mode
                callback(xobj.responseText);
            }
        };
        xobj.send(null);
    }
    
    const init = () => {
        loadJSON((response) => {
            // Parse JSON string into object
            let actual_JSON = JSON.parse(response);
        });
    }

提交回复
热议问题