AJAX overwrites variable

Asked

Viewed 29 times

0

I cannot copy the result to the variable registroJson, I’ve already lost almost a day in this trouble:

$(document).ready(function(){

  var registroJson = [];
  var url = 'xpto';  

  $.getJSON(url,function(data){

    registroJson = data; //copiando para variavel registroJson o resutado 'data' 

    // já tentei registroJson.push(data) e tabem não funciona    
  }); 

  console.log(registroJson); //o resultado no console sempre mostra [], array vazio

});

1 answer

1


Ajax is asynchronous and non-synchronous, which rotates within (is a callback):

  function(data){

    registroJson = data; //copiando para variavel registroJson o resutado 'data' 

    // já tentei registroJson.push(data) e tabem não funciona    
  }

It is only fired later because you need the request to finish first, already the console.log is fired before because it is outside the callback and you don’t have to wait for the requisition.

To understand what is asynchronous in javascript read this answer:

Although not about ajax, this answer explains the callback:

And most importantly, to understand what Ajax is there is this question:

Pro console.log work it also needs to wait for the callback, so do this:

$(document).ready(function(){
  var registroJson = [];
  var url = 'xpto';  

  $.getJSON(url,function(data){
      registroJson = data;
      console.log(registroJson);
  }); 
});
  • 1

    William thank you so much!! Surely I will read and study these links you have indicated!!!

  • @If the answer solved the problem, mark it as correct, if you do not know how to do it read this link: http://meta.pt.stackoverflow.com/q/1078/3635

Browser other questions tagged

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