0

相当奇怪的问题是,除了 .ajax 函数本身,我不能在任何地方使用数据变量(ajax 调用返回的信息)。

我确信这是一个范围问题,但是它超出了我的范围,并且将不胜感激任何指示。

$('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;
}
4

2 回答 2

2

这实际上不是范围问题,而是同步性问题。

当您的getPreviewImage函数返回时,尚未进行 ajax 调用(它是异步的,执行流程不会等待请求和响应完成),因此output仍然为 null。

您可以通过进行同步 ajax 调用或提供回调getPreviewImage而不是使用其返回值来解决此问题。

要进行同步 ajax 调用,请false作为async参数传递。请参阅文档

要使用回调,您可以这样做:

$('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);
  });
}

使用同步调用更容易(您只需将参数设置为 false),但回调逻辑通常更可取,因为它不会阻止您的脚本并允许并行请求。

于 2012-06-28T14:40:38.883 回答
1

$.ajax您可以使用jQuery 函数调用另一个函数。尝试执行以下操作。

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;
}
于 2012-06-28T14:44:08.063 回答