java - 访问ajax成功回调函数的响应数据

标签 java arrays ajax spring spring-mvc

我返回了 list<object>从我的 Controller ,它成功捕获在ajax的success()中,因为它是列表,所以它可以有 n 个对象,我想动态创建表格数据并通过迭代 data 填充相同的数据,但我无法访问 data 中的元素对象,如控制台数据所示,实际元素包装在外部对象和我的 for 循环外部对象内。请参阅随附的屏幕截图

图片引用请引用此链接:Console log

Controller 的Ajax调用:

function getSelectedTableRecords(tableId) {

    if (tableId != null && tableId != '') {
        $.ajax({
            type: "POST",
            url: baseUrl + "search",
            data: {
                tableId: tableId
            },
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    $('#applicationList > tbody').append(
                        '<tr>'
                        + '<td><h4>' + item.userId + '</h4></td>'
                        + '<td><h4>' + item.firstName + '</h4></td>'
                        + '<td><h4>' + item.lastName + '</h4></td>'
                        + '<td><h4>' + item.rollNo + '</h4></td>'
                        + '<td><h4>' + item.contact + '</h4></td>'
                        + '<td><h4>' + item.email + '</h4></td>'
                        + '<td><h4>' + item.gender + '</h4></td>'
                        + '</tr>');
                    insideData(data);
                }
            },
            fail: function (data) {
                alert('Failed to fetch records.');
            }
        });
    } else {
        // ...
    }
}

我的 Controller 代码:

@RequestMapping(value = "/search", method = RequestMethod.POST)
@ResponseBody
public List<Object> fetchTableData(@RequestParam("tableId") String tableId) {
   List<Object> userList = new ArrayList<>();
   try {
       System.out.println(" table id id " + tableId);
       if (tableId != null) {
           List<UserInfo> l = userInfoDao.findById(tableId);
           userList.add(l);
       }
       return userList;
   } catch (Exception e) {
       e.printStackTrace();
       return null;
   }
}

根据屏幕截图,我只得到一行所有 undefined值(value)观,我想做的事情,在我的图像中 7元素,所以我想迭代,我想要七行及其相应的列填充值。请建议我解决方案。

最佳答案

嗯,据我从你的日志中看到,该结构是一个数组的数组。可以使用以下方式访问元素:

success: function (data) {
    for (var i = 0; i < data[0].length; i++) {  // access the first item data[0] of outer array
         var item = data[0][i];                 // and get the nth object
         $('#applicationList > tbody').append(
            // code skipped
         );
         insideData(data);
    }
},

为什么会发生这种情况?

因为你回来List<Object>其中有一个元素 List<UserInfo> 。这个简短的操作序列将一个列表添加到一个列表中并返回它:

List<Object> userList = new ArrayList<>();           // Creates a List
List<UserInfo> l = userInfoDao.findById(tableId);    // Creates another of users
userList.add(l);                                     // Adds List to List
return userList;                                     // Returns the List to List

由于返回类型是 List<Object> ,你可能没有注意到返回的类型实际上是 List<List<UserInfo>> .

如何解决?

有两种方法,但我推荐您第二种:

  1. 我想您想将所有元素添加到外部 List并保持扁平结构。为此,您必须使用方法 List::addAll 它传递 List 中的所有元素到另一个。您已使用 List::add 它按原样将一个元素添加到列表中 - 在您的情况下,添加的元素是一个新的整个 List而不是它的元素。

  2. 更好的方法是直接返回结果。如果没有找到任何内容,则返回空 List :

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ResponseBody
    public List<UserInfo> fetchTableData(@RequestParam("tableId") String tableId) {
        try {
            List<UserInfo> userList = new ArrayList<>();
            System.out.println(" table id id " + tableId);
            if (tableId != null) {
                userList = userInfoDao.findById(tableId);
            }
            return userList;
        } catch (Exception e) {
            // log it, don't print the stacktrace...
            return Collections.emptyList()
        }
    }
    

还有什么?

我注意到您使用 POST方法,但是由于您从服务器接收数据,因此应该使用 GET方法,无论您传递一个标识要返回的实体的参数。来自 W3Schools :

  • GET用于从指定资源请求数据。
  • POST用于将数据发送到服务器以创建/更新资源。

关于java - 访问ajax成功回调函数的响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673793/

相关文章:

java - 如何简单地在消息中编写多行文本?

java - 对strut和filter的怀疑

java - 签名 Applet 和服务器端 Controller 之间的通信

javascript - 通过表单发送json对象c# mvc

javascript - 使用Ajax添加TinyMCE实例-Grails

java - GridBagLayout 中的二次 JPanel

javascript - 在 Javascript 中将 Array 对象转换为 Json

c++ - 在类中声明一个数组。 C++

ruby - 在这种情况下,正则表达式比数组比较快吗?

ruby-on-rails - 我应该使用模板来呈现 JSON 还是在 RoR 中使用 Controller 返回 JSON?