简体   繁体   中英

AJAX responsetext to global variable

    var req = new XMLHttpRequest();
    req.open("Get","/topjob/php/data.json");
    req.onload = function (){
        var ourData = JSON.parse(req.responseText);
        randerHTML(ourData);
        randerHTML2(ourData);
    req.send();
};

I want to assign responseText to global variable. how can do it

Global variables are, basically, the properties of the window object.

 var req = new XMLHttpRequest(); req.open("Get","/topjob/php/data.json"); req.onload = function (){ window.myNewVariable = req.responseText; var ourData = JSON.parse(req.responseText); randerHTML(ourData); randerHTML2(ourData); req.send(); }; 

You can just put this:

globalVariable = req.responseText;

anywhere in your code where req.responseText is defined.

But creating such global variables is definitely NOT a good idea. If you need to do so, it means that something's not right with your app's architecture.

Declare it just outside the method where this ajax call is written. Making it a global variable is a recipe for introducing unpredictable bugs if the code does not take care of it properly.

var topJobData;
var req = new XMLHttpRequest();
req.open("Get","/topjob/php/data.json");
req.onload = function (){
    topJobData = req.responseText;
    var ourData = JSON.parse(req.responseText);
    randerHTML(ourData);
    randerHTML2(ourData);
    req.send();
};

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