2014-11-04 206 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}}}"; 

希望這有助於任何其他人遇到類似的問題。