2014-11-04 205 views
1

我想要遵循数据表示的示例为Ajax数据源(对象)发现here。我使用的是asp.net,并具有以下接收我的数据,处理它并提供响应的处理程序。jquery数据表Ajax响应

public class UsersHandler : IHttpHandler 
{ 
    private const string JsHeader = @"{{""data"" {0}}}"; 


    public void ProcessRequest(HttpContext context) 
    { 
     IEnumerable<SystemUser> data = SystemUserLogic.LoadAllSystemUsers(); 

     List<SimpleUser> userlist = new List<SimpleUser>(); 
     foreach (SystemUser su in data) 
     { 
      SimpleUser simple = new SimpleUser(); 
      simple.Id = su.Id; 
      simple.FullName = su.NameFirst; 
      simple.Email = "[email protected]"; 
      userlist.Add(simple); 
     } 
     string json = JsonConvert.SerializeObject(userlist, Formatting.Indented); 
     context.Response.ContentType = "text/plain"; 
     context.Response.ContentEncoding = Encoding.UTF8; 
     context.Response.Cache.SetNoStore(); 
     context.Response.Expires = -1; 
     context.Response.Write(String.Format(JsHeader, json)); 
    } 

当我在浏览器中捕获它并通过网络流量查看数据时,它们会发送正确的响应。我的aspx页面包含以下内容。

$('#table_id').DataTable({ 
      "ajax": '/Handlers_New/UsersHandler.ashx', 
      "columns": [ 
       { "data": "Id" }, 
       { "data": "FullName" }, 
       { "data": "Email" }, 
       { "data": "KeyResource" } 
      ] 

     }); 

但是在页面加载时,我收到此错误:

数据表警告:表ID = table_id的 - JSON响应无效。有关此错误的详细信息,请参阅http://datatables.net/tn/1

输出的数据是这样的,

{"data" [ 
{ 
"Id": 1, 
"FullName": "Admin", 
"Email": "[email protected]", 
"KeyResource": false 
}, 
{ 
"Id": 2, 
"FullName": "Jon", 
"Email": "[email protected]", 
"KeyResource": false 
}, 
{ 
"Id": 3, 
"FullName": "Stephen", 
"Email": "[email protected]", 
"KeyResource": false 
}, etc..... 

请告诉我为什么我收到此错误。我应该以不同的方式操作json对象,还是缺少一些Jquery数据表?

+0

你是否包含必要的jQuery库文件?你可以添加你的表格的HTML代码?另外,看看这个[datable参考](http://www.datatables.net/manual/tech-notes/1)。确保你完全验证了返回的Json – Chris 2014-11-04 16:08:31

+0

是的,jQuery文件已经包含在正确的顺序。我的表只是简单地包含一个表格,其中包含多个用于列标题的td。我也检查了没有问题的响应,响应状态是正确的等等,返回的数据就像上面那样,从错误信息生成的那个链接之后。 :/仍坚持这个... – 2014-11-04 18:00:57

回答

1

由于jsonlint,我设法解决了我的问题。我通过它运行我的代码,事实证明我在我的jsHeader中缺少':'。因此,我不得不为:

private const string JsHeader = @"{{""data"" {0}}}"; 

什么,我现在该功能现在已经是:

private const string JsHeader = @"{{""data"": {0}}}"; 

希望这有助于任何其他人遇到类似的问题。