首页 > 解决方案 > 表格未附加 ajax 数据,而是在浏览器中显示 json 数组

问题描述

 <script>
    $(document).ready(function () {
        $('#btnClick').click(function () {
            $.ajax({
                url: '/jQueryPratice/HandleJsonArray',
                dataType: 'json',
                method: 'post',
                success: function (data) {
                    var roleTable = $('#tblRole tbody');
                    $(data).each(function (index, role) {
                        roleTable.append('<tr><td>' + role.RoleDescription + '</td><td>' + role.RoleShortDescription + '</td></tr>')
                    });
                }
            });
        });
    });
</script>

并且在视野中

<body>
<hr />
<input type="button" value="Click" id="btnClick" />
<br /><br />
    <table id="tblRole" border="1">
        <thead>
            <tr>
                <th>
                    RoleDescription
                </th>
                <th>
                    RoleShortDescription
                </th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

现在我想在单击按钮单击时附加表格。我从调用中获取数据,但它没有绑定数据,而是在浏览器上我得到纯 jaon 数组。我应该怎么做才能将数组与表绑定?

标签: c#jqueryajaxasp.net-mvc

解决方案


也许您正在将数据直接从 ajax 调用方法返回到浏览器。尝试先将数据接收到视图然后附加它。

    public ActionResult Index()
    {
        return View();
    }

在此视图中创建表格和按钮。然后使用另一种操作方法像这样返回您的集合

public ActionResult HandleJsonArray()
    {
        //get roles
        return Json(roles, JsonRequestBehavior.AllowGet);
    }

希望它对你有用。


推荐阅读