最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - jQuery.ajax() success callback store data to return - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 3, 2011 at 12:58 Bojangles 102k50 gold badges174 silver badges209 bronze badges asked Nov 3, 2011 at 12:56 OtzeOtze 1021 gold badge1 silver badge8 bronze badges 1
  • 3 Wele to the wonderful world of async! You can't do that. – SLaks Commented Nov 3, 2011 at 13:00
Add a ment  | 

5 Answers 5

Reset to default 7

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 plete

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.

发布评论

评论列表(0)

  1. 暂无评论