Can't use returned data in .ajax method of jQu

2020-02-02 03:19发布

Rather odd problem in that I cannot use the data variable (the information returned by the ajax call) anywhere but in the .ajax function itself.

I am sure this is an issue of scope, however it is one that is beyond me and would be grateful of any pointers.

$('img#test').live('click', function(e) {
    e.preventDefault();
    var test = getPreviewImage();
    alert(test); // This just gives undefined
});


function getPreviewImage()
{
  var output;

  var img_bg = $('div#preview-1 img:nth-child(1)').prop('src');
  var img_fg = $('div#preview-1 img:nth-child(2)').prop('src');


  $.ajax({
    url: "/blah.php?v=12345,

  }).done(function (data) {

    alert(data); // This gives the correct response
    output = data; // This should take the data value but still be in scope for the return statement below

  });

return output;
}

2条回答
走好不送
2楼-- · 2020-02-02 03:58

You can call another function using the $.ajax jQuery function. Try doing the following.

function getPreviewImage()
{
  var output;

  var img_bg = $('div#preview-1 img:nth-child(1)').prop('src');
  var img_fg = $('div#preview-1 img:nth-child(2)').prop('src');


  $.ajax({
    url: "/blah.php?v=12345,

  }).done(someotherFunction)

  });

}

function someotherFunction(data) {
     return data;
}
查看更多
我想做一个坏孩纸
3楼-- · 2020-02-02 04:03

This isn't really a problem of scope but of synchronicity.

When your getPreviewImage function returns, the ajax call hasn't yet be made (it's asynchronous and the execution flow doesn't wait for the request and response to be complete), so output is still null.

You can solve this by making a synchronous ajax call or by providing a callback to getPreviewImage instead of using its return value.

To make a synchronous ajax call, pass false as the async parameter. See the doc.

To use a callback, you can do this :

$('img#test').live('click', function(e) {
    e.preventDefault();
    getPreviewImage(function(test){
        // use test
    });
});


function getPreviewImage(callback) {

  $.ajax({
    url: "/blah.php?v=12345",...

  }).done(function (data) {
    callback(data);
  });
}

Using a synchronous call is easier (you just have to set a parameter to false) but the callback logic is generally preferable as it doesn't block your script and allows parallel requests.

查看更多
登录 后发表回答