【问题标题】:jQuery - how to add table rows from the ajax call?jQuery - 如何从 ajax 调用中添加表行?
【发布时间】:2018-08-21 16:06:00
【问题描述】:

我有一个应该从 ajax 调用的结果中填充的表。该表定义为:

<table id="resourceTable" class="table table-bordered table-hover">
    <thead>
        <tr>
            <th th:text="${propB}" />
            <th th:text="${text}" />
            <th th:text="${description}" />
        </tr>
    </thead>
    <tbody>
        // contents to be inserted here  
    </tbody>
</table>

如果我直接在浏览器上调用url,我会得到预期的结果:

[{"value":"value","text":"text","description":"description","propA":"propA","propB":"propB"}]

ajax 调用是:

$.ajax({
    type: "GET",
    url: ajaxUrl,
    dataType: "json",
    cache: false,
    success: function (data) {
        data = $.parseJSON(data);
        var trHTML = '';
        $(function () {
            $.each(data, function (i, item) {
                trHTML = $('<tr>').append(
                         $('<td>').text(item.propB),
                         $('<td>').text(item.text),
                         $('<td>').text(item.description)
                );
            });
            $('#resourceTable').append(trHTML);
        });
    },
    error: function (msg) {
        alert(msg.responseText);
    }
});

我知道数据对象存在,但我无法渲染表格。

我在这里错过了什么?

【问题讨论】:

  • 使用开发者工具查看带回了哪些数据。还要检查一下: dataType 是 json 所以你收到的值,如果是 json,它已经应该是 json 对象,不需要解析它。另外我会附加到 tbody 标签而不是表格。
  • 如果数据确实是你描述的形式,当你尝试$.parseJSON(data)时应该会抛出错误。如果您使用 Mozilla Firefox for dev(不知道它是否适用于其他浏览器),我知道它不再是推荐,但我强烈建议使用 Firebug 检查控制台日志和有关 javascript 和 ajax 的错误。我认为在 Firefox 47 之后不再允许安装它,但黄色 bug 对我来说是救命稻草,我并不真正关心新的,并不总是更好;),替代 Firefox 开发者版。

标签: jquery ajax html-table


【解决方案1】:

跳过

data = $.parseJSON(data)

通过在 ajax 请求中指定 dataType:'json' ,返回的对象已经是从返回的 json 解析的 javascript 对象。顺便说一句,如果您的服务器确实返回 json 作为内容类型标头,那么您甚至不需要指定数据类型。

【讨论】:

    猜你喜欢
    • 2016-05-02
    • 2014-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多