jquery中数据表调用的代码如下所示
$(document).ready(function () {
$("#tableUserList").DataTable({
"ajax": {
"url": "AdminHome.aspx/getUsersForTable",
"dataType": "json",
"cache": false,
"contentType": "application/json; charset=utf-8",
"dataSrc": "d",
"type": "GET"
},
"columns": [
{"data": "d[id]"},
{"data": "d[username]"},
{"data": "d[user_type]"},
{"data": "d[first_name]"},
{"data": "d[last_name]"},
{"data": "d[address]"},
{"data": "d[email]"},
{"data": "d[phone_no]"},
]
});
});
当我检查控制台时,没有显示错误,但是没有任何数据加载到数据表中。我的HTML表格如下
<table id="tableUserList" class="table table-hover">
<thead>
<tr>
<th>UserID</th>
<th>Username</th>
<th>UserType</th>
<th>FirstName</th>
<th>LastName</th>
<th>Address</th>
<th>Email</th>
<th>Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserId</td>
<td>Username</td>
<td>UserType</td>
<td>FirstName</td>
<td>LastName</td>
<td>Address</td>
<td>Email</td>
<td>Contact</td>
</tr>
</tbody>
</table>
并且我的ajax调用以这种格式返回数据。为简单起见,显示一行返回的数据
{
"d":[
{
"id":1,
"username":"admin",
"first_name":"admin",
"last_name":"admin",
"phone_no":"1234567210",
"address":"abc",
"email":"admin@gmail.com",
"user_type":"admin"
},
...
]
}
正确返回数据意味着我在将接收到的数据绑定到DataTable时出错了。请提出解决方案。
答案 0 :(得分:1)
我认为如果您修改了传递给"columns": [{"data": "d[id]"}, ...
的内容,您的代码就可以了。在数据属性中,您可以从数据对象传递属性名称,因此请将其更改为"columns": [{"data": "id"}, ...
,并且您还可以在传递时指定此列的标题标题属性。
我给你一个简单的javascript源类型数据示例,但它类似于ajax源数据。
$(document).ready(function () {
var data = {
"d":[
{
"id":1,
"username":"admin",
"first_name":"admin",
"last_name":"admin",
"phone_no":"1234567210",
"address":"abc",
"email":"admin@gmail.com",
"user_type":"admin"
},
{
"id":2,
"username":"user 1",
"first_name":"user",
"last_name":"first",
"phone_no":"1234567210",
"address":"address",
"email":"user@gmail.com",
"user_type":"user"
}
]
};
$("#tableUserList").DataTable({
"data": data.d,
"columns": [
{"data": "id", title: "ID"},
{"data": "username", title: "Username"},
{"data": "first_name", title: "First Name"},
{"data": "last_name", title: "Last Name"},
{"data": "phone_no", title: "Phone"},
{"data": "address", title: "Address"},
{"data": "email", title: "Email"},
{"data": "user_type", title: "Type"}
]
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<table id="tableUserList" class="table table-hover">
</table>