简体   繁体   中英

jQuery.ajax() success callback store data to return

I'm trying to get some data from a PHP script in a project right now. All examples I found searching for AJAX callback functions "use" the data already in the callback itself, but I want to fetch data and store it in a way ready to be returned.

function getEle (id) {
    var element = []; 

    $.ajax({
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;

            element[0] = id;
            element[1] = content;
            // if I alert(element[1]); here it will work! 



        }
    });
    alert(element[1]); // here it just won't :/ ("undefined")
    return element;
}

Somewhere in my script some function needs to getEle(ments) but all I get is undefined . is there a way to do what I want? Or is there maybe a better way to do this?

A solution would be to pass a callback function to getEle() :

getEle(id, callback){
  $.ajax({
    /* some options, */
    success: function(){
      var content = data;
      element[0] = id;
      element[1] = content;
      callback(element);
    }
  })
}

And then pass a function containing the code of what to do when you have the element content:

getEle('myId', function(element){
  alert(element[1]);
});

Two things are failing here:

  • Variable scope - You define the variable content inside the AJAX callback. This makes it inaccessible from the surrounding code. You could omit the var and just write content = data which makes it accessible globally.
  • Asynchronicity - Becaus AJAX is asynchronous the script following the callback will be executed before the callback was executed. The only way to solve that problem is to use the callback as it's intended to.

Take a look at this.

function getEle (id, callback) {
        var element = []; 

        $.ajax({
            url: 'slides.php',
            type: 'POST',
            data: {"id": id},
            success: function(data) {
                var content = data;
                element[0] = id;
                element[1] = content;

                callback(element);
            }
        });
    }
}

getEle ("someID", function(someElement) {
    alert(someElement);
});

Here's what's happening in your code:

  • the array "element" is initialized.
  • the AJAX call is made with a success callback function
  • while it's waiting for that AJAX to run, it goes ahead with the rest of your code and alerts element[1], which doesn't exist yet
  • the success callback runs and populates the array "element".

You might consider a global variable to solve this:

var element = []; 

function getEle (id) {
    $.ajax({
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;
            element[0] = id;      // the global "element" is set
            element[1] = content;
        }
    });
}
// element[0] will exist now, but only after the AJAX call is complete

Alternatively, you could turn your AJAX into a synchronous call:

function getEle (id) {
    var element = []; 

    $.ajax({
        async: false,   // forces synchronous call
        url: 'slides.php',
        type: 'POST',
        data: {"id": id},
        success: function(data) {
            var content = data;
            element[0] = id;
            element[1] = content;
        }
    });
    alert(element[1]); // now it is set
    return element;
}

The only other option I can see is to keep everything tied up inside the "success" callback, which you already discovered works fine.

Your callback executes some time after the rest of your code finishes.

You need to pass the value back using a callback, the way $.ajax does.

Your alert ends up being undefined because the AJAX call is asynchronous. So while that AJAX call is waiting for the server's response, the script continues on to the alert, at which point element[1] is not yet defined.

You should place your return element line inside of the success callback function.

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