【问题标题】:ASPX URL produces a JSON string, Consume with jQuery DataTableASPX URL 生成 JSON 字符串,使用 jQuery DataTable 使用
【发布时间】:2017-07-11 23:47:51
【问题描述】:

为了练习,我正在尝试将 JSOn 数据显示到我的 aspx 网页中的数据表中,但该数据表被 processing 这个词卡住了。结果当我检查控制台时,错误是 Cannot read property 'length' of undefined

这个错误是什么意思?我如何解决它?这个错误是因为我的方法错误吗?

我所做的是,首先我创建了一个 .aspx.cs 文件,该文件在调用 URL 时生成 JSON 字符串:

[{"NickName":"Bob","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Bob","LogIN":"6/6/1846 12:00:00 AM","LogOUT":"6/6/1846 12:00:00 AM"},{"NickName":"Patrick","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/6/1846 12:00:00 AM","LogOUT":"6/6/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/5/1846 12:00:00 AM","LogOUT":"6/5/1846 12:00:00 AM"},{"NickName":"Krabs","LogIN":"","LogOUT":""},{"NickName":"Sandy","LogIN":"","LogOUT":""},{"NickName":"Pearl","LogIN":"","LogOUT":""}]

然后在我应该显示数据表的 .aspx 文件上, 我写了这个脚本,这是dataTables site 上的建议:

 /*using the ajax function*/
       var tbl = $('#datatableJSONEx').DataTable({
           processing: true,
           serverSide: true,
           info: true,
           ajax: "DefaultJSONResult?THEstr=produceJSON",

           order: [[0, 'desc']],
           select: true,
           responsive: true,
           buttons: true,
           length: 10

       });

然后我在 HTML 中添加了它的表示:

        <div>

            <table id="datatableJSONEx" class="display" cellspacing="0" width="100%">                    
                 <thead>
                    <tr>
                        <th>NickName</th>
                        <th>LogIN</th>
                        <th>LogOUT</th> 
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>NickName</th>
                        <th>LogIN</th>
                        <th>LogOUT</th> 
                    </tr>
                </tfoot>
            </table>

        </div>

</div>

是什么导致了错误?解决错误后,如果我希望我的表在服务器发生更改时自动更新,这种方法是否正确?

编辑 我在我的 dataTables jQuery 中更改了这个属性: ajax: "DefaultJSONResult?THEstr=produceJSON" 进入 ajax: $.ajax("DefaultJSONResult?THEstr=produceJSON")

但是,它仍然显示正在处理中......当我在谷歌浏览器中检查元素时,我在控制台上看不到任何东西。

更新 我将 jQuery 更改为让 $.ajax() 将我的 url 转换为对象,然后将其传递给数据表的 ajax: 属性:

var jqxhr = $.ajax("DefaultJSONResult?THEstr=ProduceJSON",
            {
            success: function (data, status, xhr) { //on success
                $('p').append(status);
             },
            error: function (jqXhr, textStatus, errorMessage) { //the action was a failure, know why.
                $('p').append('ERROR: ' + errorMessage);
            }
        });



        /*using the ajax function*/
       var tbl = $('#datatableJSONEx').DataTable({
           processing: true,
           serverSide: true,
           info: true,
           ajax: jqxhr,
           sAjaxDataProp : "",
           columns: [
               { data: 'NickName'},
               { data: 'TimeIN' },
               { data: 'TimeOUT' }
           ],

           order: [[0, 'desc']],
           select: true,
           responsive: true,
           buttons: true,
           length: 10

       });

元素 p 现在返回 SUCCESS 并且控制台显示没有错误。但是数据表仍然没有返回任何内容...... JSON 字符串是返回原因的 .aspx url 吗?如何让 Jquery Datatables 接受我的格式?正确的格式是什么?

【问题讨论】:

  • 你有模型,我的意思是 C# 中与数据表列相关的类吗?
  • 数据表需要array of objects,所以你必须发送array of objects 而不是json string
  • 我明白了,system.datatable 算作对象数组吗?
  • 为了从 dbase 获取数据,我使用了 (System.Data.SQLClient),然后将其作为 JSON 字符串输出,我使用了 Newtonsoft.Json。
  • No json string 不会填充您在C# 中将其转换为list of objects 并发送list 的表格。

标签: javascript c# jquery asp.net json


【解决方案1】:

我能够通过使用数据表的ajax 属性来输出表格。我只是按照此处的说明操作我的特定 JSON 字符串的 格式

JSON 字符串

[{"NickName":"Bob","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Bob","LogIN":"6/6/1846 12:00:00 AM","LogOUT":"6/6/1846 12:00:00 AM"},{"NickName":"Patrick","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/7/1846 12:00:00 AM","LogOUT":"6/7/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/6/1846 12:00:00 AM","LogOUT":"6/6/1846 12:00:00 AM"},{"NickName":"Ward","LogIN":"6/5/1846 12:00:00 AM","LogOUT":"6/5/1846 12:00:00 AM"},{"NickName":"Krabs","LogIN":"","LogOUT":""},{"NickName":"Sandy","LogIN":"","LogOUT":""},{"NickName":"Pearl","LogIN":"","LogOUT":""}]

HTML

 <div class="col-md-4">
        <h2>JQUERY Datagrid</h2>
        <p>Free Datatables via Jquery. Data is produced via JSON data source. </p>
            <div>

                <table id="datatableJSONEx" class="display">                    
                     <thead>
                        <tr>
                            <th>NickName</th>
                            <th>LogIN</th>
                            <th>LogOUT</th> 
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
                            <th>NickName</th>
                            <th>LogIN</th>
                            <th>LogOUT</th> 
                        </tr>
                    </tfoot>
                </table>
            </div>

    </div>

..和 JS

       var tbl = $('#datatableJSONEx').DataTable({

           ajax: {
               dataSrc: "",
               url: "DefaultJSONResult?THEstr=produceJSON"
           },

           columns: [
               { data: 'NickName' },
               { data: 'LogIN' },
               { data: 'LogOUT' }
           ],
           order: [[0, 'desc']],
           select: true,
           responsive: true,
           buttons: true,
           length: 10
       });

        //we set an interval so that grid automatically reloads every afer 10 secs.
       setInterval(function () {
       tbl.ajax.reload( null, false ); // ( null, false) so user paging is not reset on reload
            }, 10000 ); //10 seconds!

(感谢 Mayank 促使我朝着正确的方向前进。我或多或少对 ajax works 的方式有了更清晰的了解。我也可以通过 JSON.ajax() success 返回值,但我最终选择了上面的代码,因为有了它,我还可以通过.ajax.reload()使网页上线)

【讨论】:

    【解决方案2】:

    如果您使用的是server side datatable,则需要将正确的dataset 发送到datatable。下面是使用asp.netserver side datatable 的工作示例

    [WebMethod]
    [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
    public static DataTableData GetData()
    {
    
       List<string[]> list = new List<string[]>();
       DataTableData data = new DataTableData();
       data.data = new List<string[]>();
    
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "1" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "2" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "3" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "4" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "5" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "6" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "7" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "8" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "9" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "10" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "11" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "12" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "13" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "14" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "15" });
       list.Add(new string[] { "Mairaj", "Ahmad", "Minhas", "16" });
    
       int start = 0;
       int length = 0;
       int draw = 0;
       int.TryParse(HttpContext.Current.Request.QueryString["start"].ToString(), out start);
       int.TryParse(HttpContext.Current.Request.QueryString["length"].ToString(), out length);
                int.TryParse(HttpContext.Current.Request.QueryString["draw"].ToString(), out draw);
    
       data.draw = draw;
       var filter = list.Skip(start).Take(length).ToList();
       data.data = filter;
    
       data.recordsFiltered = list.Count;
       data.recordsTotal = list.Count;
       return data;
    }
    
    public class DataTableData
    {
      public int draw { get; set; }
      public int recordsTotal { get; set; }
      public int recordsFiltered { get; set; }
      public List<string[]> data { get; set; }
    
     }
    

    这是数据表定义

    <table id="example" class="display" cellspacing="0" width="100%">
            <thead>
                <tr>
    
                    <th>First name</th>
                    <th>Last name</th>
                    <th>Position</th>
                    <th>ID</th>
                </tr>
            </thead>
            <tfoot>
                <tr>
                    <th>First name</th>
                    <th>Last name</th>
                    <th>Position</th>
                    <th>ID</th>
                </tr>
            </tfoot>
        </table>
    

    【讨论】:

      【解决方案3】:

      试试这个:

      $(document).ready(function() {
      var dataSet = [];
      dataSet.push(
          [1,"Sasha","Brenna","0800 1111"],
          [2,"Sage","Mia","(01012) 405872"],
          [3,"Chelsea","Allistair","076 0578 0265"],
          [4,"Uta","Savannah","070 1247 5884"],
          [5,"Remedios","Berk","0995 181 0007"],
          [6,"Ruby","Wayne","0800 1111"],
          [7,"Faith","Fredericka","(01709) 099879"],
          [8,"Myra","Harrison","070 4241 9576"],
          [9,"Drake","Miriam","0800 733635"],
          [10,"Reed","Shannon","076 8597 5067"]
      );
      
      $('#data_table').DataTable( {
          data: dataSet,
      });
      

      在您的情况下,dataSet 从 ajax() 调用中获取其值。

      Working Fiddle

      【讨论】:

      • 谢谢,但这种方法意味着数据集被编码到页面中。如果我需要它来自数据库怎么办?
      • 检查行在您的情况下,dataSet 从 ajax() 调用中获取其值。 在答案中指定。
      • 这到底是什么意思?很抱歉,我对这种方法真的很陌生。
      • 您必须使用 ajax 或传统方法将值从数据库获取到 dataSet
      • 我尝试使用像 ajax: $.ajax("DefaultJSONResult?THEstr=produceJSON") 这样的 $.ajax() 函数...但是,它仍然显示正在处理并且控制台没有显示任何内容。给定一个包含 JSON 字符串的 URL,你会如何做吗?
      猜你喜欢
      • 2015-04-03
      • 1970-01-01
      • 2011-02-02
      • 2011-04-29
      • 2011-12-28
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      相关资源
      最近更新 更多