简体   繁体   中英

Jquery .ajax() local variable can't assign to global

I have a jquery ajax code as following:

$(document).ready(function() {
  var global_arr = new Array();
  $.ajax({
    url: 'result.php',
    type: 'post',
    dataType: 'json',
    success: function(data) {
       $.each(data, function(key, value) {
          global_arr.push(value.name);
       });
       alert(global_arr); //get correct value, works fine
     }
  }); //end of ajax function
  alert(global_arr); //get null, it doesn't work properly
});

Notice the lines to alert global_arr, why I can't get the value out of $.ajax() function? Thanks anyone help on this.

Ajax takes time to complete. The function execution does not take nearly as much time. So by the time you get to your alert outside of the ajax request, the ajax request is still using time to complete (either in transmission or in server side actions).

You can always wait for the ajax method to be complete.

$(document).ready(function() {

 var global_arr = new Array();
 var complete = false;//flag to wait for ajax completion
 $.ajax({
  url: 'result.php',
  type: 'post',
  dataType: 'json',
  success: function(data) {
   $.each(data, function(key, value) {
      global_arr.push(value.name);
   });
   alert(global_arr); //get correct value, works fine
   complete = true;//mark ajax as complete
  }
 }); //end of ajax function

 (function runOnComplete(){
  if( complete ){//run when ajax completes and flag is true
   alert(global_arr);
  }else{
   setTimeout(runOnComplete,25);//when ajax is not complete then loop
  }
 })()
});

However, the most common way is to use a callback.

$(document).ready(function() {

 function runOnComplete(){//code executes once ajax request is successful
  alert(global_arr);
 }
 var global_arr = new Array();
 $.ajax({
  url: 'result.php',
  type: 'post',
  dataType: 'json',
  success: function(data) {
   $.each(data, function(key, value) {
    global_arr.push(value.name);
   });
   alert(global_arr); //get correct value, works fine
   runOnComplete();//callback
  }
 }); //end of ajax function
});

Ajax is asynchronous. At the time the JS engine reaches your non-functioning alert() line, the AJAX call has not yet had a chance to get a response from the server and set the variable.

That's why the inner alert() works. It gets executed when the response comes in from the server.

that is because alert(global_arr); //get null, it doesn't work properly alert(global_arr); //get null, it doesn't work properly runs before $.ajax has completed

My suggestion here would be to break this out in to 3 funcitons so it will make a bit more sense. You will need ajax, handelRequest, onComplete. You may also want to add and error handler to your ajax function so if it does fail it can do so with out the script locking up on the user.

$(document).ready(function () {

    var global_arr = new Array();

    $.ajax({
        url: 'result.php',
        type: 'post',
        dataType: 'json',
        success: handelRequest(data),
        error: handleError             
    });

    function handelRequest(data) {          
        $.each(data, function (key, value) {
            global_arr.push(value.name);
        });
        onComplete(global_arr); //get correct value, works fine
    }

    function onComplete(global_arr){
        // then here you can do what ever you
        // you would like with the array
        alert(global_arr);
    }

    function handleError(){
        // gracefully fail
    }

})

Ajax function runs asynchronously and before ajax function adds incoming data in your array, the outer alert function runs and for this reason alerts an empty array.

You can use async-await to make the outer alert function wait for the incoming data.

  $(document).ready(async function() {
  var global_arr = new Array();
  await $.ajax({
    url: 'result.php',
    type: 'post',
    dataType: 'json',
    success: function(data) {
       $.each(data, function(key, value) {
          global_arr.push(value.name);
       });
       alert(global_arr);
     }
  }); //end of ajax function
  alert(global_arr); //it will work fine now
});

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