如何正确地从 jQuery ajax 成功函数返回一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2195161/
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
How to return an array from jQuery ajax success function properly?
提问by ecu
TheObject = {
对象 = {
getArray: function(){
var groups = new Array;
$.ajax({
type: "POST",
url: "link.php",
success: function (data){
var counter = 0;
$('g',data).each(function(){
var group_name = $(this).find("name").text();
var group_id = $(this).find("id").text();
var group = {
id: group_id,
name: group_name
}
groups[counter] = group;
counter++;
});
return groups;
}
});
}
}
And when I try to call this method:
当我尝试调用此方法时:
var a = TheObject.getArray();
alert(a);
It returns 'undefined'. I cant figure out where is the problem. The array gets created inside the success function but I'am unable to return it properly. Thanks for your help!
它返回“未定义”。我无法弄清楚问题出在哪里。该数组是在成功函数中创建的,但我无法正确返回它。谢谢你的帮助!
回答by David Hellsing
In your code, you are looking for groups
using procedural coding after the ajax call was made. The main problem is that you are looking for groups
before the ajax call is complete.
在您的代码中,您正在寻找groups
在进行 ajax 调用后使用过程编码。主要问题是您groups
在ajax调用完成之前寻找。
Another problem is that you are returning groups to the success()
function, but the TheObject.getArray()
function returns nothing.
另一个问题是您将组返回给success()
函数,但TheObject.getArray()
函数不返回任何内容。
So you need to bring in the callback into the ajax function like this:
所以你需要像这样将回调引入到ajax函数中:
TheObject = {
getArray: function(callback) {
var groups = new Array;
$.ajax({
type: "POST",
url: "link.php",
success: function (data){
var counter = 0;
$('g',data).each(function(){
var group_name = $(this).find("name").text();
var group_id = $(this).find("id").text();
var group = {
id: group_id,
name: group_name
}
groups[counter] = group;
counter++;
});
callback.call(this,groups);
}
});
}
}
TheObject.getArray(function(a) {
// this code runs when the ajax call is complete
alert(a);
});
回答by TheRealJAG
A very simple version of David's example.
David 示例的一个非常简单的版本。
TheObject = {
getArray: function(callback) {
$.ajax({
cache: true,
type: "GET",
url: "http://www.domain.com/core/domains.php",
success: function (data){
callback.call(this,data);
}
});
}
}
TheObject.getArray(function(data) {
javascript: console.log(data);
});
回答by Teja Kantamneni
Use push
on the array. Also you want to create a type called Group and then create a new group in the loop and then push it into the array.
push
在阵列上使用。您还想创建一个名为 Group 的类型,然后在循环中创建一个新组,然后将其推送到数组中。