如何正确地从 jQuery ajax 成功函数返回一个数组? [英] How to return an array from jQuery ajax success function properly?

查看:31
本文介绍了如何正确地从 jQuery ajax 成功函数返回一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TheObject = {

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!

推荐答案

在您的代码中,您正在寻找 groups 在进行 ajax 调用后使用过程编码.主要问题是您在 ajax 调用完成之前寻找 groups.

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.

另一个问题是您将组返回给 success() 函数,但 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 ajax 成功函数返回一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆