【问题标题】:DataTables - Invalid JSON Response QueryDataTables - 无效的 JSON 响应查询
【发布时间】:2021-06-27 13:37:54
【问题描述】:

我使用 .csv 文件(逗号分隔文件)作为数据源创建了一个页面,但是当我加载该页面时,会返回一个 Invalid JSON response 错误。 当我检查 Network > XHR 时,我看不到任何错误信息,并且在 Response 选项卡下没有显示任何内容。但是,当我单击“确定”按钮关闭错误消息时,.csv 文件中的所有数据都会显示在“响应”选项卡下。

无论我在本地还是在我的网络服务器上托管文件,都会出现同样的问题。

这可能是https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js 文件中的配置问题吗?我在下面提供了我用作参考的相关标头代码:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
<style type="text/css" class="init"></style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" class="init">
$(document).ready(function() {
    $('#mrgs').DataTable( {
        "ajax": 'mydata.csv'
    } );
} );
</script>

有没有人知道是什么导致了这个问题。任何帮助将不胜感激。

【问题讨论】:

  • CSV 数据不是 JSON - 它们是完全不同的结构。 DataTables 需要 JSON 结构化数据而不是 CSV 结构化数据。另外,您的 &lt;table&gt; 元素在哪里?从数据源到表列的映射在哪里?
  • 有各种各样的例子here - 它们有助于澄清你需要做什么吗?
  • 感谢您的回复 andrewjames。表列映射没有错:
  • 类型 Qtr Year Surname Forename(s) SpseName District 页面
  • 问题一定是.csv文件不被接受。

标签: jquery datatables


【解决方案1】:

您可以将 csv 预处理为 DataTable 想要的对象值格式的数组。

这是可插入您页面的完整解决方案

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href='https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css' />
<script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<table id="mrgs" class="table"></table>
<script>
$(document).ready(function() {
    $.ajax({
        url: "./data.csv",
        context: document.body
    }).done(function(csv) {
        let allTextLines = csv.split(/\r\n|\n/);
        let headers = allTextLines[0].split(',').map(e => e.trim());
        let lines = [];
        for (let i = 1; i < allTextLines.length; i++) {
            let line = allTextLines[i].split(',') // take the comma separated line, turn into an array
                .reduce((b, a, index) => { // b is the accumulator, a is the iteration value
                    b[headers[index].toLowerCase().replace(/\s+/g, '')] = a.trim(); // set the object property and value
                    return b; // return the accumulator for our next iteration
                }, {});
        if (Object.keys(line).length === headers.length) lines.push(line)            }
        // now fix headers to be object/value pairs
        headers = headers.map((e) => ({
            title: e,
            data: e.toLowerCase().replace(/\s+/g, '')
        }))
        // console.log(headers)
        //  console.log(lines)
        $('#mrgs').DataTable({
            columns: headers,
            data: lines
        });
    });
});
</script>

$(document).ready(function() {
  let csv = `Type,Qtr,Year,Surname,Forenames,SpseName,District,Volume,Page 
  Marriages,Dec,1837,JAMES,Ann,,Mansfield,15,942 
  Marriages,Dec,1839,Karlton,Diana,,Mansfield,15,1017 
  Marriages,Dec,1841,Mepham,Elizabeth,,Mansfield,15,994 
  Marriages,Sep,1842,CASPIAN,Sophia,,Mansfield,15,617 
  Marriages,Dec,1842,Kennedy,Mark,,Mansfield,15,957
  Marriages,Dec,1843,Crampus,Elizabeth,,Mansfield,15,1034 
  Marriages,Mar,1846,Dalton,Paulina,,Mansfield,15,741 
  Marriages,Dec,1846,JAMIESON,William,,Mansfield,15,1031 
  Marriages,Dec,1848,Rodon,Reuben,,Mansfield,15,1096 
  Marriages,Mar,1849,PHILBERT,Reuben,,Mansfield,15,703 
  Marriages,Dec,1849,STARKEY,Thos,,Mansfield,15,1092 
  Marriages,Jun,1850,Porter,John,,Mansfield,15,843`
  let allTextLines = csv.split(/\r\n|\n/);
  let headers = allTextLines[0].split(',').map(e => e.trim());
  let lines = [];
  for (let i = 1; i < allTextLines.length; i++) {
    let line = allTextLines[i].split(',') // take the comma separated line, turn into an array
      .reduce((b, a, index) => { // b is the accumulator, a is the iteration value
        b[headers[index].toLowerCase().replace(/\s+/g, '')] = a.trim(); // set the object property and value
        return b; // return the accumulator for our next iteration
      }, {});
    if (Object.keys(line).length === headers.length) lines.push(line)
  }
  // now fix headers to be object/value pairs
  headers = headers.map((e) => ({
    title: e,
    data: e.toLowerCase().replace(/\s+/g, '')
  }))
  // console.log(headers)
  //  console.log(lines)
  $('#mrgs').DataTable({
    columns: headers,
    data: lines
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href='//cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css' />
<script src="//cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>

<table id="mrgs" class="table"></table>

【讨论】:

  • 感谢您的回复 Kinglish。如果我可以避免转换文件,那肯定会节省时间。但是,当我用您的代码替换文档就绪功能代码并编辑 url 行以指向 csv 文件时,仅显示 代码中的表头。没有数据显示,没有搜索字段,没有排序工具,没有显示 x 条目数下拉列表。我忽略了什么?
  • 我更新了我的答案,代码并添加了一个示例 sn-p
  • 我可以看到代码 sn-p 有效,但是当我将代码替换为:
  • $(document).ready(function() { $('#mrgs').DataTable( { let csv = First name, Last name, Address, City, State, Zip John,Doe,120 jefferson st.,Riverside, NJ, 08075 Jack,McGinnis,220 hobo Av.,Phila, PA,09119 Stephen,Tyler,7452 Terrace At the Plaza road,SomeTown, SD, 91234, Blankman,,SomeTown, SD, 00298
  • 我正在努力研究如何投票和接受答案。坦率地说,这并不明显。据我所知,提出问题的人必须单击向上箭头(答案的左上角)以支持答案,然后单击箭头下方的勾号以接受答案。我希望这是正确的。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 2018-10-31
  • 2015-04-20
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多