AJAX override variable

0

I can not copy the result to the variable registroJson , I've already lost almost a day in this problem:

$(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

});
    
asked by anonymous 14.03.2016 / 15:47

1 answer

1

Ajax is asynchronous and not synchronous, which runs inside (it's 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 triggered afterwards because it needs the request to finish first, since console.log is triggered before because it is out of callback and does not have to wait for the request.

To understand what is asynchronous in javascript, read this answer:

Although it is 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 callback , so do this:

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

  $.getJSON(url,function(data){
      registroJson = data;
      console.log(registroJson);
  }); 
});
    
14.03.2016 / 15:53