javascript jQuery.ajax() 成功回调存储数据返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7995234/
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
jQuery.ajax() success callback store data to return
提问by Otze
I'm trying to get some data from a PHP script in a project right now. All examples I found searching for AJAX callback functions "use" the data already in the callback itself, but I want to fetch data and store it in a way ready to be returned.
我现在正在尝试从项目中的 PHP 脚本中获取一些数据。我发现搜索 AJAX 回调函数的所有示例“使用”了回调本身中已有的数据,但我想获取数据并以准备好返回的方式存储它。
function getEle (id) {
var element = [];
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
// if I alert(element[1]); here it will work!
}
});
alert(element[1]); // here it just won't :/ ("undefined")
return element;
}
Somewhere in my script some function needs to getEle(ments)
but all I get is undefined
.
is there a way to do what I want? Or is there maybe a better way to do this?
在我的脚本中的某个地方需要一些函数,getEle(ments)
但我得到的只是undefined
. 有没有办法做我想做的事?或者有没有更好的方法来做到这一点?
回答by Avaq
A solution would be to pass a callback function to getEle()
:
一个解决方案是将回调函数传递给getEle()
:
getEle(id, callback){
$.ajax({
/* some options, */
success: function(){
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
})
}
And then pass a function containing the code of what to do when you have the element content:
然后传递一个包含元素内容时要执行的代码的函数:
getEle('myId', function(element){
alert(element[1]);
});
回答by buschtoens
Two things are failing here:
这里有两件事失败了:
- Variable scope- You define the variable content insidethe AJAX callback. This makes it inaccessible from the surrounding code. You could omit the
var
and just writecontent = data
which makes it accessible globally. - Asynchronicity- Becaus AJAX is asynchronous the script following the callback will be executed before the callback was executed. The only way to solve that problem is to use the callback as it's intended to.
- 变量范围-您可以定义变量的内容里面的AJAX回调。这使得它无法从周围的代码访问。您可以省略
var
and 只写content = data
使其可全局访问。 - 异步性- 因为 AJAX 是异步的,回调之后的脚本将在回调执行之前执行。解决该问题的唯一方法是按预期使用回调。
Take a look at this.
看看这个。
function getEle (id, callback) {
var element = [];
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
callback(element);
}
});
}
}
getEle ("someID", function(someElement) {
alert(someElement);
});
回答by Blazemonger
Here's what's happening in your code:
这是您的代码中发生的事情:
- the array "element" is initialized.
- the AJAX call is made with a success callback function
- while it's waiting for that AJAX to run,it goes ahead with the rest of your code and alerts element[1], which doesn't exist yet
- the success callback runs and populates the array "element".
- 数组“元素”被初始化。
- AJAX 调用是使用成功回调函数进行的
- 在等待 AJAX 运行时,它会继续执行您的其余代码和警报元素 [1],这些元素尚不存在
- 成功回调运行并填充数组“元素”。
You might consider a global variable to solve this:
您可能会考虑使用全局变量来解决此问题:
var element = [];
function getEle (id) {
$.ajax({
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id; // the global "element" is set
element[1] = content;
}
});
}
// element[0] will exist now, but only after the AJAX call is complete
Alternatively, you could turn your AJAX into a synchronous call:
或者,您可以将 AJAX 转换为同步调用:
function getEle (id) {
var element = [];
$.ajax({
async: false, // forces synchronous call
url: 'slides.php',
type: 'POST',
data: {"id": id},
success: function(data) {
var content = data;
element[0] = id;
element[1] = content;
}
});
alert(element[1]); // now it is set
return element;
}
The only other option I can see is to keep everything tied up inside the "success" callback, which you already discovered works fine.
我能看到的唯一其他选择是将所有内容都绑定在“成功”回调中,您已经发现它可以正常工作。
回答by SLaks
Your callback executes some time after the rest of your code finishes.
您的回调在您的其余代码完成后执行一段时间。
You need to pass the value back using a callback, the way $.ajax
does.
您需要使用回调将值传回,方法$.ajax
确实如此。
回答by maxedison
Your alert ends up being undefined because the AJAX call is asynchronous. So while that AJAX call is waiting for the server's response, the script continues on to the alert, at which point element[1]
is not yet defined.
您的警报最终未定义,因为 AJAX 调用是异步的。因此,当 AJAX 调用正在等待服务器的响应时,脚本继续处理警报,此时element[1]
尚未定义。
You should place your return element
line inside of the success
callback function.
您应该将您的return element
行放在success
回调函数内。