我正在尝试在ASP.Net中使用jQuery Datatables插件的服务器端功能。Ajax请求返回有效的JSON,但是表格中没有显示任何内容。
最初我在发送Ajax请求时遇到了一些问题。我收到了一个"Invalid JSON primitive"错误。我发现数据需要以字符串而不是JSON序列化形式发送,如此帖子所述:http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/。我不太确定如何修复它,所以我尝试在Ajax请求中添加了这个:
"data": "{'sEcho': '" + aoData.sEcho + "'}"
如果上述方法最终生效,我将稍后添加其他参数。目前我只是想让某些内容显示在我的表格中。
返回的JSON看起来不错并且验证通过,但是post中的sEcho未定义,我认为这就是为什么没有数据加载到表格中的原因。
那么,我做错了什么?我是否走错了路或者很傻?有人之前遇到过这个问题或者有任何建议吗?
以下是我的jQuery代码:
$(document).ready(function()
{
$("#grid").dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bServerSide":true,
"sAjaxSource": "GridTest.asmx/ServerSideTest",
"fnServerData": function(sSource, aoData, fnCallback) {
$.ajax({
"type": "POST",
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"url": sSource,
"data": "{'sEcho': '" + aoData.sEcho + "'}",
"success": fnCallback
});
}
});
});
HTML:
<table id="grid">
<thead>
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>UserID</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
</table>
Webmethod:
<WebMethod()> _
Public Function ServerSideTest() As Data
Dim list As New List(Of String)
list.Add("testing")
list.Add("chad")
list.Add("testing")
Dim container As New List(Of List(Of String))
container.Add(list)
list = New List(Of String)
list.Add("testing2")
list.Add("chad")
list.Add("testing")
container.Add(list)
HttpContext.Current.Response.ContentType = "application/json"
Return New Data(HttpContext.Current.Request("sEcho"), 2, 2, container)
End Function
Public Class Data
Private _iTotalRecords As Integer
Private _iTotalDisplayRecords As Integer
Private _sEcho As Integer
Private _sColumns As String
Private _aaData As List(Of List(Of String))
Public Property sEcho() As Integer
Get
Return _sEcho
End Get
Set(ByVal value As Integer)
_sEcho = value
End Set
End Property
Public Property iTotalRecords() As Integer
Get
Return _iTotalRecords
End Get
Set(ByVal value As Integer)
_iTotalRecords = value
End Set
End Property
Public Property iTotalDisplayRecords() As Integer
Get
Return _iTotalDisplayRecords
End Get
Set(ByVal value As Integer)
_iTotalDisplayRecords = value
End Set
End Property
Public Property aaData() As List(Of List(Of String))
Get
Return _aaData
End Get
Set(ByVal value As List(Of List(Of String)))
_aaData = value
End Set
End Property
Public Sub New(ByVal sEcho As Integer, ByVal iTotalRecords As Integer, ByVal iTotalDisplayRecords As Integer, ByVal aaData As List(Of List(Of String)))
If sEcho <> 0 Then Me.sEcho = sEcho
Me.iTotalRecords = iTotalRecords
Me.iTotalDisplayRecords = iTotalDisplayRecords
Me.aaData = aaData
End Sub
返回的 JSON:
{"__type":"Data","sEcho":0,"iTotalRecords":2,"iTotalDisplayRecords":2,"aaData":[["testing","chad","testing"],["testing2","chad","testing"]]}