简体   繁体   中英

Retrieving JSON data read with ajax and callback function

Apologies for the very beginner question.

I'm trying to use this answer to read in data in a JSON file into my javascript. I've pasted the code from the answer directly into the top of my javascript (changing pathToFile.json obviously). What I'm not sure about is what I'm supposed to do where the "do something with your data" comment is. I just want to have the parsed data object available to the rest of my code, but being extremely new to javascript I don't really understand how the callback function works. I can see the data from the JSON file logged in the console when I run it but every (no doubt dumb) thing I've tried to do to 'get it out' of the function hasn't worked -- I get a ReferenceError: data is not defined message when I try to refer to it later.

Here's the code from the other answer:

function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send(); 
}

// this requests the file and executes a callback with the parsed result once
//   it is available
fetchJSONFile('pathToFile.json', function(data){
    // do something with your data
    console.log(data);
});

That's because data is defined as a local variable in the scope of onreadystatechange and the callback functions. Assuming you do not want to try jQuery or some other framework, you may try it like this to bind the data to a global variable:

var app = (function(){

    var json;

    function fetchJSONFile(path, callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200) {
                    var data = JSON.parse(httpRequest.responseText);
                    if (callback) callback(data);
                }
            }
        };
        httpRequest.open('GET', path);
        httpRequest.send(); 
    }

    // this requests the file and executes a callback with the parsed result once
    //   it is available
    fetchJSONFile('pathToFile.json', function(data){
        // do something with your data
        json = data;
    });

    return { getData : function()
    {
        if (json) return json;
        else return false;//or show some msg that 'data is not loaded yet'
    }};

})();

// you now have access to your data via:
app.getData(); // will either be false or contain the data 

Regarding your question about the callback function, it is a function that you pass to fetchJSONFile that will get called once the data is retrieved from the httpRequest. Since that is asynchronous you don't control when the callback function gets called - it will be called once the request completes with an OK status (given your current implementation). So everything under "do something with your data" is what will be executed once the data is retrieved and parsed (that is the body of your callback function).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM