除了函数本身之外,不能在jQuery的.ajax方法中使用返回的数据 [英] Can't use returned data in .ajax method of jQuery anywhere but the function itself

查看:200
本文介绍了除了函数本身之外,不能在jQuery的.ajax方法中使用返回的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}


推荐答案

这不是范围问题,而是同步问题。

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

当你的 getPreviewImage 函数返回,尚未进行ajax调用(它是异步的,执行流不等待请求和响应完成),所以输出仍然为空。

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.

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

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

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

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);
  });
}

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

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.

这篇关于除了函数本身之外,不能在jQuery的.ajax方法中使用返回的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆