JavaScript XMLHttpRequest Scope Function

1
function getMensages(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '../mensagens.php');
    xhr.send();
    xhr.onload=function(){
        if (xhr.readyState==4 && xhr.status==200){
            jsonText = xhr.responseText;
            jsonObj = JSON.parse(jsonText);
        }
       return jsonObj;
   }
}

getMensages();

console.log(jsonObj);

How do I get the jsonObj variable out of the scope of the xhr.onload() function and out of the getMensages() function? When calling the function xhr.onload() it is already returning object I want but I need the object in the variable outside the scopes.

    
asked by anonymous 25.02.2015 / 03:56

2 answers

3

To have this variable in the global scope you can do window.jsonObj = jsonObj; (which is better than setting without using var ), but this will not solve the problem. Remember that AJAX is asynchronous and when you call it the value will only be passed to the variable jsonObj when the server responds, which implies that the code you have already ran and the console.log() was registered without the variable has been completed.

You have to adapt your code to run within the xhr.onload function. In case of your code this console.log() should be there to record the right value.

xhr.onload=function(){
    if (xhr.readyState==4 && xhr.status==200){
        jsonText = xhr.responseText;
        jsonObj = JSON.parse(jsonText);
        console.log(jsonObj);  // aqui será chamado quando a resposta tiver chegado
    }
}
    
25.02.2015 / 11:48
0
function getMensages(callback){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', '../mensagens.php');
    xhr.send();
    xhr.onload=function(){
        if (xhr.readyState==4 && xhr.status==200){
            jsonText = xhr.responseText;
            jsonObj = JSON.parse(jsonText);
            if(callback) callback(jsonObj);
        }
       //return jsonObj;
   }
}

var cback = function(jsonObj) {
  console.log(jsonObj);
};

getMensages(cback);
    
06.03.2015 / 15:06