我试图弄清楚如何将来自AJAX调用的集合绑定到DataTable,但遗憾的是每次我收到一条错误,说JSON无效(但不是!)
我有一个名为"响应"的返回对象它有一个名为"收件人"它的类型为#34;收件人"并有一些道具:
姓 姓 EmailAddress的
即:response.Recipients 在clientide调用中转换为data.Recipients(见下文)
我不确定如何让它绑定 - 任何想法?
这是我目前的代码:
$.ajax({
contentType: 'application/json',
url: '@Url.Action("GetRecipients")',
type: 'POST',
dataType: 'json',
data: jsonPayload,
cache: false,
success: function (data) {
if (data.Success) {
$('#tblRecipients').DataTable({
"data": data.Recipients,
"columns": [{
"Firstname": "Firstname",
"Lastname": "Lastname",
"EmailAddress": "EmailAddress"
}]
});
}
else {
alert(data.FailureInformation);
}
},
error: function (xhr, status, error) {
alert('There was a problem obtaining the selected recipient details. Please try again later');
}
});
肯定不是这么难吗?
是的,数据是正确的。我可以在Recipients对象中看到来自调用的3个项目。
感谢您的任何指示!
编辑 - 示例json:
[{
"Firstname": "Tim",
"Lastname": "Hughes",
"EmailAddress": "th@test.com"
}, {
"Firstname": "Joe",
"Lastname": "Bloggs",
"EmailAddress": "jb@test.com"
}]
答案 0 :(得分:2)
好。没人想通了。而且我相信OP想要一个答案。如果您在
中使用""
,问题显然不是
"columns": [{
"Firstname": "Firstname",
"Lastname": "Lastname",
"EmailAddress": "EmailAddress"
}]
但您应该在data
更正
columns
columns: [
{ data: "Firstname" },
{ data: "Lastname" },
{ data: "EmailAddress" }
]
参见演示 - >的 http://jsfiddle.net/0f9Ljfjr/796/ 强>
答案 1 :(得分:0)
您应该使用aoColumns而不是列
让我们考虑以下示例
var test = [ {"Firstname":"Tim","Lastname":"Hughes","EmailAddress":"th@test.com"},{"Firstname":"Joe","Lastname":"Bloggs","EmailAddress":"jb@test.com"} ];
$('#tblRecipients').DataTable({
"aaData": test,
"aoColumns": [
{ "mDataProp": "Firstname" },
{ "mDataProp": "Lastname" },
{ "mDataProp": "EmailAddress" }
]
});
我还创建了JS小提琴,请查看https://jsfiddle.net/bj3r2bnf/3/
答案 2 :(得分:0)
更改此
$('#tblRecipients').DataTable({
"data": data.Recipients,
"columns": [{
"Firstname": "Firstname",
"Lastname": "Lastname",
"EmailAddress": "EmailAddress"
}]
});
到此:
$('#tblRecipients').DataTable({
data: data.Recipients,
columns: [{
"Firstname": "Firstname",
"Lastname": "Lastname",
"EmailAddress": "EmailAddress"
}]
});
我不确定原因,但使用data
和columns
代替字符串属性名称也适用于@ mauliksakhare的jsFiddle。