简体   繁体   中英

saving ajax response to array with Jquery

I got a Jquery ajax call that gets a json response from a php file i got, the json response is great and I can console log the response correctly, however I don't seem to be able to save the information outside the ajax result, it wont update the array. the code looks like this and I posted the result below.

window.array={name: 'john',color:'red'};    

 console.log(array['name']);
 console.log(array['color']);

$.ajax({
    url : 'getJsons.php',
    type : 'POST',
    data : data,
    dataType : 'json',
    success : function (data) {

      array['name'] = data['name'];
      array['color'] = data['color'];
      console.log(array['name']);
      console.log(array['color']);
     }        
});

 console.log(array['name']);
 console.log(array['color']);

this will result in the following console:

 john
 red

 john
 red

 marry
 blue

So I get the console right the first time but it seem to load the script after the ajax call before the ajax call, why is that? because that makes it impossible for me to use the ajax result in the rest of the code since it's being fetched after the script is already loaded. Is there a way to get the ajax to be run before the rest?

Since you cannot possibly tell when the ajax response from the server is arriving, AJAX is asynchronous by default. This means that the $.ajax get's triggered and then the javascript engine continues to execute the rest of your code (in your example the two console.log s outside the ajax call). Somewhere in the future, the ajax call may (or may not) get the response from the server (and notifies this by changing it's state). At this point the javascript engine will process the so called "callback" function - code which shall be executed when the ajax call is finished. You define your callback function as the success parameter of the ajax method.

That's why the correct way to execute your code is to run everything which depends on the result in the callback function. Put everything directly in there, or declare a separate function which you then can invoke in the success function:

$.ajax({
    /*...*/,
    success : function (data) {

      array['name'] = data['name'];
      array['color'] = data['color'];

      /* either put all your dependent code here */

      /* or just call a callback function: */
      callback(data);

     }        
});

/* code to be executed after the ajax call */
function callback(data){

   // work with the response here
   console.log(data);

}

Bad idea ahead:

Alternatively you could tell the call to be synchronously (which is bad, because your browser basically is frozen while it waits for the answer from the server) and keep your code as it is.

$.ajax({
      /*...*/,
      async : false,     
});
// risk some waiting time (possibly the full duration of a timeout!!)
// the browser is locked during this time

// continue normally
console.log(array['name']);
console.log(array['color']);

What is happening is the code after your query is being ran before the ajax call has finished. Your array has been populated, don't worry but because AJAX runs asynchronously it will only assign the values after the ajax call.

If for example you set a 10 second timeout after the ajax call (depending on how long the AJAX call took to do) and then called the array values, you would find them populated (provided the AJAX has ran and gone through the callback function properly).

So in your code, step by step here is what happens.

You display the values from the array which shows john red

You make the AJAX call, when this call has completed it will perform your success: function

The ajax call takes (lets say) 1 second to complete

Whilst your page is waiting for the call to complete and update the values it moves onto the next bit of code which displays the array, as the array hasn't been updated yet as success hasn't been called it still displays john red

1 seconds later the success function is called, assigns the new names to the array and prints them out.

The ajax call is asynchronous which means the rest of the code will be executed regardless of when the ajax is executed and returned. If your code depends on the result, wrap it in a function and call it from the callback of the ajax (success function).

I don't know if this stuff is a standard stuff, but it's work:

var xmlURL = "Data/XML/"+GetURLParameter("xml");
var xmlInto = {};

$.get(xmlURL, function(xml) {
    $(xml).find("line").each(function(){
        xmlInto[line_number] = line_info;
    });             
}, 'xml');

console.log(xmlInto);

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