我无法从 ajax 命令填充 jQuery 数据表。
这是 webAPI 代码(UtentiController):
' GET: api/Utenti
<HttpGet>
Public Function GetUtentis() As IEnumerable(Of Utenti)
Using WFe As WorkForceEntities = New WorkForceEntities
Return WFe.Utentis.ToList
End Using
End Function
这是客户端代码:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
paging: true,
sort: true,
searching: true,
"ajax": {
"url": '/api/utenti/',
"type": "get",
"datatype": "json",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
},
"columns": [
{ "data": "Nome", "autoWidth": true },
{ "data": "Cognome", "autoWidth": true },
{ "data": "Username", "autoWidth": true },
{ "data": "GruppoDiLavoro", "autoWidth": true },
{ "data": "ProfiloFunzionalità", "autoWidth": true },
]
})
})
</script>
我认为问题出在 json 字符串上。 ajax 命令返回不正确的 json,缺少初始子字符串 {"data":
[ { "IDutente": 2, "Operatore": "Admin", "Password": "1234", "LivelloDiAccesso": 1, "Nome": "Admin", "Cognome": "Admin", "Username": "Admin", "GruppoDiLavoro": "Admin", "ProfiloFunzionalità": "Admin", "Attivo": true, "DataCreazione": "2017-08-30T00:00:00", "DataScadenza": "2025-12-31T00:00:00", "Mail": "nothing" }, { "IDutente": 3, "Operatore": "MS", "Password": "1234", "LivelloDiAccesso": 2, "Nome": "Admin", "Cognome": "S", "Username": "M", "GruppoDiLavoro": "Admin", "ProfiloFunzionalità": "Admin", "Attivo": true, "DataCreazione": "2017-08-30T00:00:00", "DataScadenza": "2025-12-31T00:00:00", "Mail": "nothing" } ]
如果我像这样加载一个 json 文件 ("ajax": "../UtentiData.json",)
{ "data": [ { "IDutente": 2, "Operatore": "Admin", "Password": "1234", "LivelloDiAccesso": 1, "Nome": "Admin", "Cognome": "Admin", "Username": "Admin", "GruppoDiLavoro": "Admin", "ProfiloFunzionalità": "Admin", "Attivo": true, "DataCreazione": "2017-08-30T00:00:00", "DataScadenza": "2025-12-31T00:00:00", "Mail": "nothing" }, { "IDutente": 3, "Operatore": "MS", "Password": "1234", "LivelloDiAccesso": 2, "Nome": "Admin", "Cognome": "S", "Username": "M", "GruppoDiLavoro": "Admin", "ProfiloFunzionalità": "Admin", "Attivo": true, "DataCreazione": "2017-08-30T00:00:00", "DataScadenza": "2025-12-31T00:00:00", "Mail": "nothing" } ] }
代码运行良好,jQuery 数据表已正确填充。
我该怎么做才能很好地使用 Json webAPI? 谢谢
最佳答案
您可以使用“平面数组数据源”。
将您的代码更改为:
<script>
$(document).ready(function () {
var oTable = $('#myDatatable').DataTable({
paging: true,
sort: true,
searching: true,
"ajax": {
"url": '/api/utenti/',
"type": "get",
"dataSrc": "",
error: function (xhr, status, error) {
alert(xhr.responseText);
}
},
"columns": [
{ "data": "Nome", "autoWidth": true },
{ "data": "Cognome", "autoWidth": true },
{ "data": "Username", "autoWidth": true },
{ "data": "GruppoDiLavoro", "autoWidth": true },
{ "data": "ProfiloFunzionalità", "autoWidth": true },
]
})
})
参见 example .
关于javascript - jquery 数据表从 web API 接收到不正确的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46033169/