Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

javascript - Can't use returned data in .ajax method of jQuery anywhere but the function itself

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...