简体   繁体   中英

Store JSON data in a variable with vanilla JavaScript

I'm trying to access data from a JSON file but the result of the console is undefined .

The GET response is good, the function works but I don't know how to access the response.

function AJAX_JSON_Req(url) {
    var AJAX_req = new XMLHttpRequest();
    AJAX_req.open("GET", url, true);
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function() {
        if(AJAX_req.readyState == 4 && AJAX_req.status == 200){
            return JSON.parse(AJAX_req.responseText);
        }
    };

    AJAX_req.send();
}

var q = AJAX_JSON_Req('questions.json');

console.log(q); //undefined

http://codepen.io/gsg/pen/LEEeMg

Remember that this is an asynchronous function. Try using a callback instead and see if you have more success.

function AJAX_JSON_Req(url, callback) {
    var AJAX_req = new XMLHttpRequest();
    AJAX_req.open("GET", url, true);
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function() {
        if(AJAX_req.readyState == 4 && AJAX_req.status == 200){
            callback(JSON.parse(AJAX_req.responseText));
        }
    };

    AJAX_req.send();
}

AJAX_JSON_Req('questions.json', function (q) {
  console.log(q);
});

AJAX stands for Asyncronous JavaScript and XML.

This means that when your function ends you don't have the data yet.

onreadystatechange is an event listener. It's a non-standard form of:

AJAX_req.addEventListener("readystatechange", function () {
    // state changed
});

A simple solution would be to pass in a callback, like:

AJAX_JSON_Req("questions.json", function (reply) {
    console.log(reply);
});

And have:

AJAX_req.addEventListener("readystatechange", function () {
    // check state == 4
    callback(JSON.parse(AJAX_req.responseText));
});

A common approach of dealing with asynchronousness is the use of Promises. This avoids callback hell .

So you'll get something like:

AJAX_JSON_Req("questions.json").done(function (reply) {
    console.log(reply);
});

Promises are not natively available (yet) but you can write your own implementation or use one of the popular frameworks.

Now AJAX_JSON_Req("questions.json") returns something: a Promise. You don't have the value yet, but you have the promise that eventually you will get it.

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