如何返回Ajax调用的结果后,函数的值已经到来? [英] How to return the value of a function after the result of an ajax call has come?
本文介绍了如何返回Ajax调用的结果后,函数的值已经到来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function getfoo() {
var foo = "";
$.get("foofile.html", function (data) {
foo = data;
});
return foo;
}
但后来因为脚本是异步的,则返回。这显然不是我想要的。
But then since the script is asynchronous, it will return "". That's obviously not what I want.
于是我尝试这样做:
function getfoo() {
var foo = "";
$.get("foofile.html", function (data) {
foo = data;
});
for (;;) {
if (foo != "") {
return foo;
break;
}
}
}
和我预料到的工作,但事实并非如此。为什么不呢?而且可以有人提出一个解决方案吗?
And I expected that to work, but it didn't. Why not? And can someone suggest a solution?
推荐答案
您应该使用回调传递给函数,让它处理你的数据。
You should use a callback pass to the function and let it deal your data.
function getfoo(callback) {
var foo = "";
$.get("foofile.html", function (data) {
callback(data);
// do some other things
// ...
});
}
getfoo(function(data) {
console.log(data);
});
这篇关于如何返回Ajax调用的结果后,函数的值已经到来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文