我正在使用ajax和jquery绑定一个数据表。但我得到一个错误,如"数据表警告:表id=datatable -无效的JSON响应。">
$(document).ready(function () {
$.ajax({
type: "post",
url: "../../loader.svc/gettabledata",
data: '{}',
contenttype: "application/json; charset=utf-8",
datatype: "json",
success: onsuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function onsuccess(responce) {
$('#datatable').DataTable(
{
"ajax":
{
"datasrc": function (responce) {
var jsonObj;
jsonObj = $.parseJSON(responce.d)
return jsonObj.d;
}
},
"columns": [
{ "data": "ID" },
{ "data": "customername" },
{ "data": "LoginName" }
]
});
}
回复文本:[{"ID":1,"CustomerName"; "John";LoginName"; "John"}]">
您有两个ajax调用(jQuery调用和DataTables调用),其中只需要一个ajax调用。
如果你想使用jQuery ajax调用获取数据,你可以使用DataTablesdata
选项将数据传递给DataTables。为此,您需要将datatableajax
部分替换为data
选项。
因为我没有您的JSON提供程序进行测试,我将使用公开可用的"jsonplaceholder"URL:
$(document).ready(function() {
$.ajax({
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
//data: '{}',
//contenttype: "application/json; charset=utf-8",
//datatype: "json",
success: onsuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
});
function onsuccess(response) {
//console.log(response);
$('#example').DataTable( {
"data": response, // this passes your data to DataTables
"columns": [
{ "title": "User ID", "data": "userId" },
{ "title": "ID", "data": "id" },
{ "title": "Title", "data": "title" }
]
} );
}
注意以下三行…
data: '{}',
contenttype: "application/json; charset=utf-8",
datatype: "json",
…并不是我的演示工作所必需的。
如果愿意,可以通过只使用datattables ajax调用来简化上述方法。在这种情况下,您需要在DataTable定义的ajax
部分中使用dataSrc
:
$(document).ready(function() {
var table = $('#example').DataTable( {
ajax: {
method: "GET",
url: "https://jsonplaceholder.typicode.com/posts",
dataSrc: ""
},
"columns": [
{ "title": "User ID", "data": "userId" },
{ "title": "ID", "data": "id" },
{ "title": "Title", "data": "title" }
]
} );
} );
这将给出与第一个示例相同的结果。
小提示:你的问题中有个小错别字:"datasrc": function (responce)
应该是dataSrc
而不是datasrc
。