我正在开发我的ASP.Net Web应用程序,我必须使用Ajax数据源填充
HTML表,我正在使用jQuery DataTables插件.
HTML代码:
<table class="table table-striped table-hover table-bordered display" id="example" cellspacing="0" width="100%">
<thead>
<tr>
<th>Prctice Group Risk No
</th>
<th>Practice_Group
</th>
<th>Risk_Category
</th>
</tr>
</thead>
</table>
JavaScript代码:
$('#example').DataTable({
"ajax": {
"dataType": 'json',"contentType": "application/json; charset=utf-8","type": "POST","url":"index.aspx/Risky"
},"columns": [
{ "data": "Prctice_Group_Risk_No" },{ "data": "Practice_Group" },{ "data": "Risk_Category" }]
});
这是我的Web方法我正在调用获取对象列表的JSON响应
[WebMethod]
[ScriptMethod]
public static string Risky()
{
return JsonConvert.SerializeObject(riskList);
}
来自服务器的JSON响应:
d:"[{"Prctice_Group_Risk_No":1,"Practice_Group":"M&A","Risk_Category":"Conflicts of Interests"},{"Prctice_Group_Risk_No":2,"Practice_Group":"abc","Risk_Category":"Client Care and Communication"}]
如jquery DataTables的官方网站所述,返回的JSON响应似乎很好
http://www.datatables.net/examples/ajax/objects.html
但是表中没有填充任何数据,我在Firebug控制台中收到以下错误
TypeError: f is undefined
解决方法
默认情况下,jQuery DataTables以下列格式预期Ajax源数据.
{
"data": [
]
}
如果数据格式不同,则需要使用ajax.dataSrc来定义表数据的数据属性(在您的示例中为d).
我不是ASP.NET专家,但似乎你用JSON格式对数据进行两次编码.
对于当前的服务器端代码,请尝试以下JavaScript代码:
$('#example').DataTable({
"ajax": {
"dataType": 'json',"url":"index.aspx/Risky","dataSrc": function (json) {
return $.parseJSON(json.d);
}
},{ "data": "Risk_Category" }
]
});
有关此错误和其他常见控制台错误的详细信息,请参阅jQuery DataTables: Common JavaScript console errors.