不能在 jQuery 的 .ajax 方法中的任何地方使用返回的数据,但函数本身 [英] Can't use returned data in .ajax method of jQuery anywhere but the function itself
问题描述
比较奇怪的问题是我不能在 .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屋!