Javascript Xmlhttprequest Scope Function

Asked

Viewed 92 times

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 variable jsonObj outside the scope of the function xhr.onload() and out of function getMensages()? When calling the function xhr.onload() is already returning object I want but need the object in the variable outside the scopes.

  • http://answall.com/questions/26767/fazer-um-post-com-ajax-e-json-com-javascript-puro?rq=1

  • You can put the die into a global variable: window.jsonObj = jsonObj;

  • Good morning Kadu, maybe your question seems to be about callbacks, maybe this answer will help you: http://answall.com/a/45721/3635

2 answers

3

To have this variable in the global scope you can do window.jsonObj = jsonObj; (which is better than defenir without using var), but that won’t solve the problem. Remember that AJAX is open and when you call the value will only be passed to the variable jsonObj when the server responds, which implies that the code you have has already run and the console.log() was recorded without the variable having been completed.

You have to adapt your code to run within the function xhr.onload. In the case of your code 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
    }
}

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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.