DataTables does not display data

2019-09-01 22:02发布

问题:

I'm trying the jQuery DataTables control. The problem is that I cannot display data.

HTML is:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>DataTables Test</title>
  <script src="Scripts/jquery-1.10.2.min.js"></script>
  <link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
  <script src="Scripts/DataTables/jquery.dataTables.js"></script>
  <link href="Content/Site.css" rel="stylesheet" />
</head>

<script>
  var d = [
    { "Id": 3, "ActivityID": 91, "OperationType": 0, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
    { "Id": 4, "ActivityID": 91, "OperationType": 4, "UserID": 4183, "Comments": "", "ActionDate": "2006-03-19T12:26:01.673" },
    { "Id": 5, "ActivityID": 92, "OperationType": 0, "UserID": 5688, "Comments": "", "ActionDate": "2006-03-20T12:05:40.563" }
  ];

  $(document).ready(function () {

    $('#example').dataTable({
      "ajax": {
        "url": "WebService1.asmx/GetData",
        "type": "POST",
        "dataSrc": "",
        "contentType": "application/json; charset=utf-8"
      },
      //"data": d,
      "columns": [
          { "data": "Id" },
          { "data": "ActivityID" },
          { "data": "OperationType" },
          { "data": "UserID" },
          { "data": "Comments" },
          { "data": "ActionDate" }
      ]
    });


    var table = $('#example').DataTable();
    alert('There are' + table.data().length + ' row(s) of data in this table');

  });
</script>

<body>
  <form id="form1" runat="server">
    <div>

      <table id="example" class="display">
        <thead>
          <tr>
            <th>ActivityHistoryID</th>
            <th>AH_ActivityID</th>
            <th>AH_OperationType</th>
            <th>AH_UserID</th>
            <th>AH_Comments</th>
            <th>AH_TimeStamp</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
  </form>
</body>
</html>

If I comment out the Ajax code and uncomment the

//"data": d,

It works fine. The d variable is the JSON data that I get from the service using firefox->developer->network->xhr->response dialog.

I read many posts and I tried many things but I can't make it work. Any help? Thanks.

EDIT: Service Code:

namespace JsonTest
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string GetData()
        {
            var list = ActivityHistory.GetAll(); // List<ActivityHistory>
            var s = Newtonsoft.Json.JsonConvert.SerializeObject(list);

            return s;
            //return "{\"aaData\":" + s + "}";
        }
    }
}

EDIT 21/07/2015: I've done some changes in HTML code and it's working with a little bug. While loading I see for a moment at the top of the page the headers of the table element (ActivityHistoryID, AH_ActivityID, AH_OperationType, AH_UserID, AH_Comments, AH_TimeStamp). After that it's working fine (for 60.000 rows!!!).

The new-changed code is:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTest.aspx.cs" Inherits="JsonTest.DataTablesTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>DataTables Test</title>
  <script src="Scripts/jquery-1.10.2.min.js"></script>
  <link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
  <script src="Scripts/DataTables/jquery.dataTables.js"></script>
  <link href="Content/Site.css" rel="stylesheet" />

  <script>

    $(document).ready(function () {

      $.ajax({
        type: "post",
        url: "WebService1.asmx/getdata",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          var myData = $.parseJSON(data.d);

          $('#example').DataTable({
            "data": myData,
            "columns": [
                { "data": "Id" },
                { "data": "ActivityID" },
                { "data": "OperationType" },
                { "data": "UserID" },
                { "data": "Comments" },
                { "data": "ActionDate" }
            ]
          });
        }
      });

    });
</script>
</head>

<body>
  <form id="form1" runat="server">
    <div>
      <table id="example" class="display">
        <thead>
          <tr>
            <th>ActivityHistoryID</th>
            <th>AH_ActivityID</th>
            <th>AH_OperationType</th>
            <th>AH_UserID</th>
            <th>AH_Comments</th>
            <th>AH_TimeStamp</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
  </form>
</body>
</html>

My last hope is that I 'm using JQuery 1.10.2 instead of 1.11.1 which is in the examples of datatables site.

It 's the third day of trying and still I cannot figure it out.

EDIT 22/7/2015

That is the code that works. Far from examples.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataTablesTestWorking.aspx.cs" Inherits="JsonTest.DataTablesTestWorking" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>DataTables Test</title>
  <script src="Scripts/jquery-1.11.3.min.js"></script>
  <link href="Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
  <script src="Scripts/DataTables/jquery.dataTables.js"></script>
  <link href="Content/Site.css" rel="stylesheet" />

  <script>


    $(document).ready(function () {
      $('#example').hide();

      $.ajax({
        type: "POST",
        url: "WebService1.asmx/GetData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
          $('#example').show();

          var myData = $.parseJSON(data.d);

          $('#example').DataTable({
            "data": myData,
            "columns": [
                { "data": "Id" },
                { "data": "ActivityID" },
                { "data": "OperationType" },
                { "data": "UserID" },
                { "data": "Comments" },
                { "data": "ActionDate" }
            ]
          });
        }
      });


    });
  </script>
</head>

<body>
  <form id="form1" runat="server">
    <div>
      <table id="example" class="display">
        <thead>
          <tr>
            <th>ActivityHistoryID</th>
            <th>AH_ActivityID</th>
            <th>AH_OperationType</th>
            <th>AH_UserID</th>
            <th>AH_Comments</th>
            <th>AH_TimeStamp</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>
    </div>
  </form>
</body>
</html>

回答1:

Modify your ajax call - make it asynchronous

"ajax": {
        "url": "WebService1.asmx/GetData",
        "type": "POST",
        "async" : false,
        "contentType": "application/json; charset=utf-8"
      }

Now your data will be binded only after the ajax request is completed from your service. It worked for me.

In your server-side code , use printwriter to send the json data as a string.

PrintWriter out = resp.getWriter(); 
result.put("iTotalRecords", total); 
result.put("iTotalDisplayRecords", totalRecordCount); 
result.put("aaData", array); 
resp.setContentType("text/jsonp"); 
out.print(result);

Or else use gson to conver your list of objects to json array
e.g.,

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
  String json = gson.toJson(dataTableObject);
  out.print(json);

NOTE : aaData needs to be set else your data will not be binded.



回答2:

According to this post option contentType: 'application/json; charset=UTF-8' and type: 'POST' is indeed required to invoke an ASP.NET AJAX web method.

However, in order to send JSON-encoded parameters rather than URL-encoded parameters, you need to use ajax.data option to encode parameters into string in JSON format.

$('#example').dataTable({
  "ajax": {
    "url": "WebService1.asmx/GetData",
    "type": "POST",
    "contentType": "application/json; charset=utf-8",
    "dataType": "json",
    "data": function ( d ) {
       return JSON.stringify( d );
    },
    "dataSrc": "d",
  },
  "columns": [
      { "data": "Id" },
      { "data": "ActivityID" },
      { "data": "OperationType" },
      { "data": "UserID" },
      { "data": "Comments" },
      { "data": "ActionDate" }
  ]
});