我正在尝试将 jQuery Datatables 插件的服务器端功能与 ASP.Net 一起使用。ajax 请求返回有效的 JSON,但表中没有显示任何内容。
我最初在 ajax 请求中发送的数据有问题。我收到“无效的 JSON 原始”错误。我发现数据需要在字符串中而不是 JSON 序列化,如本文所述:http ://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-与-aspnet-ajax/。我不太确定如何解决这个问题,所以我尝试在 ajax 请求中添加它:
"data": "{'sEcho': '" + aoData.sEcho + "'}"
如果上述方法最终有效,我稍后会添加其他参数。现在我只是想让一些东西出现在我的桌子上。
返回的 JSON 看起来没问题并且可以验证,但是帖子中的 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()> _
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"]]}