javascript 返回 AJAX 回调返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9041321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
return AJAX callback return
提问by DrXCheng
For example I have a function:
例如我有一个功能:
var f1 = function(arg) {
var a;
$.ajax({
...
success: function(data) {
a = f2(data);
//return a;
}
});
//return a;
}
var f3 = function() {
a = f1(arg);
}
How can I return a
after AJAX get data
in f1
?
我怎样才能返回a
AJAX后得到data
的f1
?
回答by Adam Rackis
You can't return the result of your ajax request since the request is asynchronous (and synchronous ajax requests are a terribleidea).
您无法返回 ajax 请求的结果,因为该请求是异步的(并且同步 ajax 请求是一个糟糕的主意)。
Your best bet will be to pass your own callback into f1
您最好的选择是将您自己的回调传递给 f1
var f1 = function(arg, callback) {
$.ajax({
success: function(data) {
callback(data);
}
});
}
Then you'd call f1
like this:
然后你会这样调用f1
:
f1(arg, function(data) {
var a = f2(data);
alert(a);
}
);
回答by Dave Newton
Short, easy answer: you can't.
简短而简单的答案:你不能。
You couldmake a
a global, but you're subject to timing issues.
你可以做a
一个全局的,但你会受到时间问题的影响。
Better to either:
最好是:
- Pass in a callback to run in the Ajax success, or
- Use jQuery's
.when
/.then
construct, or - Just do the work in the callback.
- (Yeah, you could make the call synchronous. Please don't.)
- 传入一个回调来运行在 Ajax 成功,或者
- 使用 jQuery 的
.when
/.then
构造,或 - 只需在回调中完成工作即可。
- (是的,您可以使调用同步。请不要。)
回答by spinon
The easiest way to do this is to make the ajax call synchronous. Meaning in your f1 function setup the ajax call with async: false so that the function doesn't move on until the call is completed and the data returned.
最简单的方法是使 ajax 调用同步。意思是在您的 f1 函数中使用 async: false 设置 ajax 调用,以便函数在调用完成并返回数据之前不会继续运行。
回答by cambraca
You seem to need to make the ajax call synchronous. You can do that like this:
您似乎需要使 ajax 调用同步。你可以这样做:
$.ajax({
...
async: false,
success: ...
});
return a;
This way the JS execution will pause until the call returns and the success
function runs.
这样 JS 执行将暂停,直到调用返回并且success
函数运行。
Of course there is the issue of sync calls. It's best if you refactor your code so that you do what you need to do with the a
variable in the success
callback.
当然还有同步调用的问题。最好重构代码,以便a
对success
回调中的变量执行所需的操作。
Building on this idea, suppose your f3
function was something like this:
基于这个想法,假设你的f3
函数是这样的:
var f3 = function() {
a = f1(arg);
alert(a); //i.e. "do something" with "a"
}
You could do this instead:
你可以这样做:
var f3 = function() {
f1(arg);
}
var f3_callback = function(a) {
alert(a); //i.e. "do something" with "a"
}
So, your success function would look like this:
因此,您的成功函数将如下所示:
success: function(data) {
a = f2(data);
f3_callback(a);
}
I hope this is clear!
我希望这很清楚!