以JSON格式接收正确的数据但无法将其绑定到jquery数据表

时间:2017-07-13 06:18:43

标签: javascript jquery json ajax

我有$.ajax以JSON格式提取数据。但是我无法使用jquery的数据表将它绑定到我的表。 js代码如下

$(document).ready(function () {
$.ajax({
    type: "POST",
    url: "Result.aspx/getUsers",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        console.log(data.d);
        var dataParsed = $.parseJSON(data.d);
        console.log(dataParsed);
        $('#myTable').DataTable({
            "aadData": data.d,
            "columns": [
        { "data": "id" },
        { "data": "username" },
        { "data": "first_name" },
        { "data": "last_name" },
        { "data": "phone_no" },
        { "data": "address" },
        { "data": "email" },
        { "data": "user_type" },
        ]
        });
      }
    });
 });

控制台中没有显示错误,但绑定到我的表的数据也没有。 html代码如下:

<table id="myTable">
<thead>
    <tr>
        <td>UserId</td>
        <td>UserName</td>
        <td>FirstName</td>
        <td>LastName</td>
        <td>PhoneNumber</td>
        <td>Address</td>
        <td>EmailId</td>
        <td>UserType</td>
    </tr>
</thead>

请告诉我任何解决方案以及发生这种情况的原因

1 个答案:

答案 0 :(得分:1)

您正在解析json数据并在变量中分配但在Datatable中没有使用它,所以使用,

"aaData": dataParsed, // its aaData not aadData

而不是

"aadData": data.d,

您还有另一个错误(可能是) aaData ,但您使用的是 aadData 。此外,您需要解析您的JSON,并需要创建一个数据数组,如

var dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "$170,750"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "$86,000"],
  ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
  ["Airi Satou", "Accountant", "Tokyo", "$162,700"],
  ["Brielle Williamson", "Integration Specialist", "New York", "$372,000"]
];

$(document).ready(function() {
  $('#example').DataTable({
    data: dataSet,
    columns: [{
        title: "Name"
      },
      {
        title: "Position"
      },
      {
        title: "Office"
      },
      {
        title: "Salary"
      }
    ]
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />

<table id="example" class="display" width="100%"></table>