我想将JSON数据插入到我的表中,但我可以使它工作,我一直收到错误:
数据表请求第0行的未知参数0
var myTable = $('#my_logs').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true
});
$( "#getResults" ).click(function() {
$.ajax({
url: "http://www.myurl.com/data",
data: {
"from_date": from_date,
"to_date": to_date
},
type: "POST",
timeout: 30000,
dataType: "json", // "xml", "json"
success: function(logs) {
$.each(logs, function( index, value ) {
myTable.clear().draw();
myTable.row.add({
"Date": "1234",
"User Name": "1234",
"Class": "1234",
"Function": "1234",
"Action": "1234",
"Description": "1234"
}).draw();
});
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
});
我从AJAX获得的数据回应了类似的内容:
[
{
"log_time":"2015-12-27 09:42:21",
"user_name":"Me",
"class_name":"login",
"class_function":"authentication",
"action_title":"User login",
"action_description":"I am logged in"
},
{
"log_time":"2015-12-27 09:42:21",
"user_name":"me",
"class_name":"dashboard",
"class_function":"index",
"action_title":"Admin dashboard",
"action_description":"I am logged in"
}
]
答案 0 :(得分:3)
你快到了。我正确地添加columns
,看到这个工作JSFiddle:https://jsfiddle.net/annoyingmouse/gx3ktawn/
基本上,您需要告诉DataTable如何处理您提供的数据,还需要确保在每次迭代中都不清除数据; - )。
告诉DataTable您的数据结构也有助于您可以单独添加每一行。您也可以添加整个数组(myTable.clear().rows.add(logs).draw();
)而不是清除表,迭代日志中的行并添加每个行然后绘制表。
var jsonData = [{
"log_time": "2015-12-27 09:42:21",
"user_name": "Me",
"class_name": "login",
"class_function": "authentication",
"action_title": "User login",
"action_description": "I am logged in"
}, {
"log_time": "2015-12-27 09:42:21",
"user_name": "me",
"class_name": "dashboard",
"class_function": "index",
"action_title": "Admin dashboard",
"action_description": "I am logged in"
}];
var myTable = $('#my_logs').DataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": true,
"data": [],
"columns": [{
"title": "Date",
"data": "log_time"
}, {
"title": "User Name",
"data": "user_name"
}, {
"title": "Class",
"data": "class_name"
}, {
"title": "Function",
"data": "class_function"
}, {
"title": "Action",
"data": "action_title"
}, {
"title": "Description",
"data": "action_description"
}]
});
$(document).ready(function() {
$("#getResults").click(function() {
$.ajax({
url: '/echo/json/',
data: {
json: JSON.stringify(jsonData)
},
type: "POST",
timeout: 30000,
dataType: "json", // "xml", "json"
success: function(logs) {
myTable.clear();
$.each(logs, function(index, value) {
myTable.row.add(value);
});
myTable.draw();
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
});
});
希望有所帮助。