除了函数本身之外,不能在jQuery的.ajax方法中使用返回的数据

相当奇怪的问题是我不能在.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; } 

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

当你的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),但回调逻辑通常更可取,因为它不会阻止您的脚本并允许并行请求。

您可以使用$.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; }