问题描述
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!
推荐答案
在你的code,你正在寻找集团
使用程序编码Ajax调用后,进行。主要的问题是,你正在寻找的集团
之前Ajax调用完成。
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.
另外一个问题是,你正在返回群体对成功()
的功能,但 TheObject.getArray()
函数返回什么。
Another problem is that you are returning groups to the success()
function, but the TheObject.getArray()
function returns nothing.
所以,你需要把在回调到像这样的AJAX功能:
So you need to bring in the callback into the ajax function like this:
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);
});
这篇关于如何返回从jQuery的阿贾克斯成功正常工作数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!