我无法设法将这个JSON数据放入DataTable中 [英] I can't manage to put this JSON data inside DataTables

查看:85
本文介绍了我无法设法将这个JSON数据放入DataTable中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,情况就是这样。有一个带有表格的HTML页面,它使用 DataTable 插件。我必须在表格中显示我从jQuery POST调用中收到的数据,但我似乎总是会得到错误,并且在如何去做这件事上迷失方向。



这是来自POST调用的响应:

  [idoperatore:10,nome_cognome:Daniele Torrini,tariffa_westo:50.00,tariffa_interno:0.00,tariffa_viaggio:30.00,idtariffa_westo:11,idtariffa_interno :16,idtariffa_viaggio:13,attivo:1,rs:0,iniziali:DT},{idoperatore:12,nome_cognome:Irene Cavallettotariffa_esterno : 75.00, tariffa_interno: 45.00, tariffa_viaggio: 30.00, idtariffa_esterno:9 idtariffa_interno:15, idtariffa_viaggio:13, attivo:1, RS:1 iniziali:IC},{idoperatore:14,nome_cognome:Sandra Moschetti,tariffa_westo:50.00,tariffa_interno:0.00,tariffa_viaggio:30.00, idtariffa_esterno:11 idtariffa_interno:16, idtariffa_viaggio:13, attivo:1, RS:0, iniziali: SM},{ idoperatore:15, nome_cognome: Federica Coucourde,tariffa_westo:90.00,tariffa_interno:0.00,tariffa_viaggio:30.00,idtariffa_esterno:8,idtariffa_interno:16,idtariffa_viaggio:1 3,attivo:1,rs:0,iniziali:FC},{idoperatore:16,nome_cognome:Matteo Belgero,tariffa_westo:75.00,tariffa_interno : 0.00, tariffa_viaggio: 30.00, idtariffa_esterno:9 idtariffa_interno:16, idtariffa_viaggio:13, attivo:1, RS:0, iniziali: MB },{idoperatore:17,nome_cognome:Luca Belgero,tariffa_esterno:90.00,tariffa_interno:0.00,tariffa_viaggio:30.00,idtariffa_esterno:8,idtariffa_interno :16,idtariffa_viaggio:13,attivo:1,rs:0,iniziali:LB,{idoperatore:18,nome_cognome:Federico Bottoni,tariffa_esterno : 50.00, tariffa_interno: 0.00, tariffa_viaggio: 30.00, idtariffa_esterno:11 idtariffa_interno:16, idtariffa_viaggio:13, attivo:1, RS:0 iniziali:FB},{idoperatore:19,nome_cognome:Giuseppe Pantaleo,tariffa_westo:60.00,tariffa_interno:0.00,tariffa_viaggio:30.00, idtariffa_esterno:10 idtariffa_interno:16, idtariffa_viaggio:13, attivo:1, RS:0, iniziali: GP},{ idoperatore:20, nome_cognome: 马特eo Ferrario,tariffa_westo:90.00,tariffa_interno:75.00,tariffa_viaggio:30.00,idtariffa_westo:8,idtariffa_interno:9,idtariffa_viaggio:13,attivo: 1,iniziali:MF},{idoperatore:21,nome_cognome:Alessandro Mazzeranghi,tariffa_westo:100.00,tariffa_interno:0.00 tariffa_viaggio:30.00,idtariffa_westo:7,idtariffa_interno:16,idtariffa_viaggio:13,attivo:1,rs:0,iniziali:AM}] 

我无法修改该通话,因此我必须处理该通话。我只需访问包含该回调响应的变量,但是我可以根据需要转换或修改该数据。



这就是HTML表格的样子:

 < table class =display nowrapid =table_operatori> 
< thead>
< tr>
< th>
< span>< / span>
< / th>
< th class =mdl-data-table__cell - 非数字> Nome e Cognome< / th>
Tariffa Esterno< / th>
Tariffa Interno< th>
Tariffa Viaggio< / th>
Attivo?< / th>
RS?< / th>
< / tr>
< / thead>
< tbody id =table_operatori_tbody>
< / tbody>
< / table>

表中的列数与JSON中的字段数不同,因为JSON中的字段以id开头必须是隐藏值,之前用作HTML元素的属性,以便在以后使用它们。这也是空头的原因:表格之前实际上是用纯HTML填充的,并且前面有一个复选框来选择行,如下所示:

  data.forEach(function(element){
element [attivo] ==1?element [attivo] =Si:element [attivo] = 否;
元素[rs] ==1?element [rs] =Si:element [rs] =否;

var i = element ['idoperatore'];
var tableRow ='< tr>< td>< label class =mdl-checkbox mdl -js-checkbox mdl-js-ripple-effect mdl-data -table__selectfor =table_operatori_checkbox_row ['+ i +']>< input type =checkboxid =table_operatori_checkbox_row ['+ i +']class =mdl-checkbox__inputonClick =fOperatore_Checkbox_SelectUnique(' + i +')/>< / label>< / td>'
tableRow + ='< td class =mdl-data-table__cell - non-numericid =table_operatori_nomecognome_row [ '+ i +']>'+ element ['nome_cognome'] +'< / td> ;
tableRow + ='< td id =table_operatori_tariffaesterno_row ['+ i +']idtariffa ='+ element [idtariffa_westo] +'>'+ element ['tariffa_westo'] +' < / TD>';
tableRow + ='< td id =table_operatori_tariffainterno_row ['+ i +']idtariffa ='+ element [idtariffa_interno] +'>'+ element ['tariffa_interno'] +'< ; / TD>';
tableRow + ='< td id =table_operatori_tariffaviaggio_row ['+ i +']idtariffa ='+ element [idtariffa_viaggio] +'>'+ element ['tariffa_viaggio'] +'< ; / TD>';
tableRow + ='< td id =table_operatori_attivo_row ['+ i +']>'+ element ['attivo'] +'< / td>';
tableRow + ='< td id =table_operatori_rs_row ['+ i +']>'+ element ['rs'] +'< / td>';
tableRow + ='< td class =mdl-data-table__cell - non-numericid =table_operatori_iniziali_row ['+ i +']>'+ element ['iniziali'] +'< ; / TD>< / TR>';

$(#table_operatori_tbody)。append(tableRow);

这个工作,从某种意义上说(除了非常难看)这意味着表格已经形成,您可以选择我们想要的行并在以后采取行动。但是,您无法对表格中的任何行进行排序或筛选。

尽管如此,我仍然愿意维护丑陋的HTML构建,因为它意味着让DataTable工作。 row.add()你可以添加一个元素,我也试过,改变.append(tableRow):
$ b $ .DataTable()。row.add($。parseHTML(tableRow));
这也没有工作,并给出了同样的错误。同样在桌面上显示:显示对象图片



在初始化时,我没有将数据放入表中。该表必须初始化为空,并在稍后添加响应中的行。我尝试过(data是包含服务器响应的变量):

  $(#table_operatori)。 。数据表()rows.add(数据); 

哪个会去掉很多丑陋的HTML建筑物,但会给出错误:


DataTables警告:表id = table_operatori - 针对第0行第1列请求未知参数1。有关此错误的更多信息,请参阅 http://datatables.net/tn/4


因此,通过查看这个技术笔记链接,它可能会说表头中的列数多于表格主体中的列数,所以我完全匹配了我得到的字段,在定义表格时,认为如果可行的话,我最终可以隐藏不需要的列。

  $(#table_offerte)。DataTable({
paging:false,
info:false ,
列:[
{title:idoperatore},
{title:nome_cognome},
{title:tariffa_esterno},
{title :tariffa_interno},
{title:tariffa_viaggio},
{title:idtariffa_esterno},
{title:idtariffa_interno},
{title: idtariffa_viaggio},
{title:attivo},
{title:rs},
{title:iniziali}
]
}) ;

但它仍然给出相同的错误。如果我将表结构与DataTable初始化匹配,它也会这样:

  columns:[
{title:idoperatore },
{title:nome_cognome},
{title:tariffa_westo},
{title:tariffa_interno},
{title:tariffa_viaggio} ,
{title:attivo},
{title:rs},
{title:iniziali}
]


  DataTable({ajax:{url:something.json ,dataSrc:}}); 

问题是它需要url:property所要求的数据,我不能这么做,因为我只有包含JSON的data变量。



我还应该提到,通过维护旧的HTML构建并将其附加到表体中,可以使表工作正常并显示内容,像这样,但是当你尝试排序或过滤任何东西时,它就会消失,因为DataTable不会 t实际上它里面有行,只是HTML。
我不知道如何在那里获取这些数据。我希望我能清楚地解释一切,否则随时提出任何问题,我会尽我所能澄清。

提前感谢您的帮助。

解决方案

文档有点令人困惑,因为有很多不同的方式来设置表格,并且它几乎是一个人(Allan Jardine)编写插件并记录它。

首先,你不需要任何表头。将您的HTML改为:

 < table class =display nowrapid =table_operatori>< / table> ; 

如果您想将ids或类添加到 tbody 标签,那么您还需要添加它们。但是,首先,这就是您需要的所有HTML。



这里令人困惑的是,许多Allan的例子包括硬编码到HTML中的数据,没有JSON或AJAX或任何涉及。当你这样做时,你需要设置HTML标题,所有的单元格以及其他所有内容。例如,在他的一个示例中查看HTML(这一个)并亲自看到这一点。然后,当他转向JSON示例时,他会提取数据,但他会将标题保留在中。而且,您可以 如果你从JSON提取数据,你可以用HTML th 标签,或者您可以使用(或 colDefs )选项执行此操作。你不需要这样做。这从文档中不太清楚,因为在大多数例子中,Allan确实这样做。

无论您指定标头,他们必须匹配JSON订阅源的列数。如果他们不这样做,你会得到某种形式的错误。此外,如果您同时使用 th ,则 必须与您的JSON匹配字段计数,否则你会得到这个错误。这就是为什么你会得到你的错误。您正确匹配了您的定义,但您在表格定义中留下了一些 th 标签。解决方案是完全删除 th 标签。



我会假设您离开的原因出一些 th 标签是你的印象是这是让列不可见的方式。这不是,因为我上面描述的原因。定义列是否可见的最简单方法(以及定义许多其他可能的属性,列出了这里)在你的数组中:只需将列的可见选项设置为。 (你也可以在类中使用 th 标签并在CSS中设置 visibility:none ,但这样做更简单。 )



此外,列上的标题值是 title columns 该列的数组。所以,你需要让它看起来像你想要的样子,而不是把你的JSON字段放在那里。

最后,通过 data 选项,您正在阅读文档的错误部分,在运行 dataTable()时使用AJAX从URL中拉取JSON。您的数据已经存在于您的POST数据中,因此您不需要这样做。因此,请阅读。看看第二个例子,它显示了一个对象数组作为数据源。从我看到的JSON字符串中,您应该添加一个像这样的选项:

  data:myPOSTResponse,

将所有这些放在一起:

  $(#table_offerte)。DataTable({
paging:false,
info:false,
data:myPOSTResponse,
columns:[
{visible:false},//这是你不想看到的ID,不需要给它一个标题
{title:Nome e Cognome,className:mdl-data-table__cell - 非数字},
{title:Tariffa Esterno},
{title:Tariffa Interno},
{title:Tariffa Viaggio},
{visible:false},
{visible:false},
{visible:false},
{title:Attivo?},
{title:RS? },
{title:Iniziali,className:mdl-data-table__cell - 非数字}
]
});

如果您还没有做其他有趣的事情,那会让您跑步。 :)
$ b 编辑:正如DocCobra在评论中提到的那样,您还必须在这里指定 data:选项,因为数组元素是对象。如果他们是自己的数组,那么你不需要。


So, the situation is this. There is a HTML page with a table in it, that is using the DataTables plugin. I have to show data that I'm receiving from a jQuery POST call in the table, but I always seem to get errors and am lost in how to go about doing that.

This is what the response from the POST call looks like:

[{"idoperatore":10,"nome_cognome":"Daniele Torrini","tariffa_esterno":"50.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":11,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"DT"},{"idoperatore":12,"nome_cognome":"Irene Cavalletto","tariffa_esterno":"75.00","tariffa_interno":"45.00","tariffa_viaggio":"30.00","idtariffa_esterno":9,"idtariffa_interno":15,"idtariffa_viaggio":13,"attivo":1,"rs":1,"iniziali":"IC"},{"idoperatore":14,"nome_cognome":"Sandra Moschetti","tariffa_esterno":"50.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":11,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"SM"},{"idoperatore":15,"nome_cognome":"Federica Coucourde","tariffa_esterno":"90.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":8,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"FC"},{"idoperatore":16,"nome_cognome":"Matteo Belgero","tariffa_esterno":"75.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":9,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"MB"},{"idoperatore":17,"nome_cognome":"Luca Belgero","tariffa_esterno":"90.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":8,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"LB"},{"idoperatore":18,"nome_cognome":"Federico Bottoni","tariffa_esterno":"50.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":11,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"FB"},{"idoperatore":19,"nome_cognome":"Giuseppe Pantaleo","tariffa_esterno":"60.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":10,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"GP"},{"idoperatore":20,"nome_cognome":"Matteo Ferrario","tariffa_esterno":"90.00","tariffa_interno":"75.00","tariffa_viaggio":"30.00","idtariffa_esterno":8,"idtariffa_interno":9,"idtariffa_viaggio":13,"attivo":1,"rs":1,"iniziali":"MF"},{"idoperatore":21,"nome_cognome":"Alessandro Mazzeranghi","tariffa_esterno":"100.00","tariffa_interno":"0.00","tariffa_viaggio":"30.00","idtariffa_esterno":7,"idtariffa_interno":16,"idtariffa_viaggio":13,"attivo":1,"rs":0,"iniziali":"AM"}]

I have no way of modifying the call, I have to work with that. I just have access to the variable that contains that response from the callback, but I can however transform or modify that data if needed.

This is what the HTML table looks like:

<table class="display nowrap" id="table_operatori">
  <thead>
    <tr>
      <th>
        <span></span>
      </th>
      <th class="mdl-data-table__cell--non-numeric">Nome e Cognome</th>
      <th>Tariffa Esterno</th>
      <th>Tariffa Interno</th>
      <th>Tariffa Viaggio</th>
      <th>Attivo?</th>
      <th>RS?</th>
      <th class="mdl-data-table__cell--non-numeric">Iniziali</th>
    </tr>
  </thead>
  <tbody id="table_operatori_tbody">
  </tbody>
</table>

There are not the same number of columns in the table as fields in the JSON because the fields in JSON starting with "id" have to be hidden values, and were used before as attributes of the HTML elements, to use them in later moments. It's also the reason for the empty header: the table was actually filled with pure HTML before, and had a checkbox in front to select the row, like this:

data.forEach(function (element) {
    element["attivo"] == "1" ? element["attivo"] = "Si" : element["attivo"] = "No";
    element["rs"] == "1" ? element["rs"] = "Si" : element["rs"] = "No";

    var i = element['idoperatore'];
    var tableRow = '<tr><td><label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select" for="table_operatori_checkbox_row[' + i + ']"><input type="checkbox" id="table_operatori_checkbox_row[' + i + ']" class="mdl-checkbox__input" onClick="fOperatore_Checkbox_SelectUnique(' + i + ')" /></label></td>'
    tableRow += '<td class="mdl-data-table__cell--non-numeric" id="table_operatori_nomecognome_row[' + i + ']">' + element['nome_cognome'] + '</td>';
    tableRow += '<td id="table_operatori_tariffaesterno_row[' + i + ']" idtariffa="' + element["idtariffa_esterno"] + '">' + element['tariffa_esterno'] + '</td>';
    tableRow += '<td id="table_operatori_tariffainterno_row[' + i + ']" idtariffa="' + element["idtariffa_interno"] + '">' + element['tariffa_interno'] + '</td>';
    tableRow += '<td id="table_operatori_tariffaviaggio_row[' + i + ']" idtariffa="' + element["idtariffa_viaggio"] + '">' + element['tariffa_viaggio'] + '</td>';
    tableRow += '<td id="table_operatori_attivo_row[' + i + ']">' + element['attivo'] + '</td>';
    tableRow += '<td id="table_operatori_rs_row[' + i + ']">' + element['rs'] + '</td>';
    tableRow += '<td class="mdl-data-table__cell--non-numeric" id="table_operatori_iniziali_row[' + i + ']">' + element['iniziali'] + '</td></tr>';

    $("#table_operatori_tbody").append(tableRow);

This worked, in a sense, (apart from being extremely ugly) meaning that the table formed and you could select rows like we wanted and act on those later. But you couldn't sort, or filter with search, any of the rows in the table.
Still, I was willing to maintain the ugly HTML building if it meant getting the DataTable to work, since with .row.add() you can add a element, I tried that as well, changing the .append(tableRow) with:
.DataTable().row.add($.parseHTML(tableRow)); This didn't work either, and gave the same error. Also displayed this on the table though: Displays object picture

At the moment of initialization, I don't have the data to put inside the table. The table has to be initialized empty, and rows from the response added at a later time. I tried (with "data" being the variable containing the response from the server):

$("#table_operatori").DataTable().rows.add(data);

Which would remove a lot of the ugly HTML building, but it gives error:

DataTables warning: table id=table_operatori - Requested unknown parameter '1' for row 0, column 1. For more information about this error, please see http://datatables.net/tn/4

So, by looking at that tech-notes link, it says that it may be that you have more columns in the table head than in the table body, so I matched exactly the fields that I get, when defining the table, thinking that I may eventually be able to hide the columns that I don't need if that works.

    $("#table_offerte").DataTable({
      paging: false,
      info: false,
      columns: [
        { title: "idoperatore" },
        { title: "nome_cognome" },
        { title: "tariffa_esterno" },
        { title: "tariffa_interno" },
        { title: "tariffa_viaggio" },
        { title: "idtariffa_esterno" },
        { title: "idtariffa_interno" },
        { title: "idtariffa_viaggio" },
        { title: "attivo" },
        { title: "rs" },
        { title: "iniziali" }
      ]
    });

But it still gives the same error. It also does if I match the table structure with the DataTable initialization :

      columns: [
        { title: "idoperatore" },
        { title: "nome_cognome" },
        { title: "tariffa_esterno" },
        { title: "tariffa_interno" },
        { title: "tariffa_viaggio" },
        { title: "attivo" },
        { title: "rs" },
        { title: "iniziali" }
      ]

Documentation from DataTables also says that it looks inside a data: property when looking at JSON data, and you have to specify if it is not an object but an array by setting an empty string in the dataSrc property:

DataTable({ ajax: { url: "something.json", dataSrc: "" } });

The problem is that it requires the data being requested by the url: property, and I cannot do that, because I only have the "data" variable which contains the JSON.

I should also mention that by maintaining the old HTML building and appending it inside the table body, makes the table work and display stuff right, like this, but of course as soon as you try to sort or filter anything, it all disappears because the DataTable doesn't ACTUALLY have the rows inside it, just the HTML does. I have no idea how to get this data in there. I hope I explained everything clearly, otherwise feel free to ask anything and I will try my best to clarify.
Thanks in advance for any help.

解决方案

The doc is a bit confusing, because there are so many different ways to set up a table, and it's pretty much one guy (Allan Jardine) both writing the plugin and documenting it.

First, you don't need any table headers. Change your HTML to this:

 <table class="display nowrap" id="table_operatori"></table>

If you want to add ids or classes to tbody tags, then you'll need to add them in as well. But to start, this is all the HTML you need.

What's confusing here is that a lot of Allan's examples include the data hard-coded into the HTML, with no JSON or AJAX or anything involved. When you do that, then you do need to set up the HTML headers, and all the cells, and everything else. Take a look at the HTML in one of his examples (this one, for example) and see this for yourself. And then, when he moves on to JSON examples, he pulls the data but he leaves the headers in. And again, you can put them in, but don't have to.

Rather, if you're pulling your data from JSON, you can either specify your headers with HTML th tags or you can do it with the columns (or colDefs) option. You don't need to do both. This isn't as clear from the doc as it might be, since in most of the examples Allan does do both.

Whichever way you specify the headers, they have to match the column count of the JSON feed. If they don't, you'll get some form of the error you're getting. Furthermore, if you use both column and th, they both have to match your JSON field count or you'll get that error. That's why you're getting your error. You matched your columns definition correctly, but you've left some th tags out in your table definition. The solution is to remove the th tags entirely.

I'm going to presume that the reason that you left out some th tags is that you are under the impression that that's the way to make the column invisible. It isn't, for the reasons I've described above. The easiest way to define whether a column is visible or not (as well as define a lot of other possible attributes, listed here) is in your columns array: just set the column's visible option to false. (You could also use th tags with a class and set visibility:none in CSS, but this is simpler. Less to keep track of.)

Also, the title value on a column is the value for title in your columns array for that column. So, you need to make it look the way you want it, not put the name of your JSON field there.

Finally, with the data option, you're reading the wrong part of the documentation, which is about how to pull JSON from a URL using AJAX at the time you run dataTable(). You have the data already in your POST data, so you don't need to do that. So, read this instead. Have a look at the second example, which shows an array of objects as a data source. From what I see of your JSON string, you should just have to add an option like this:

data: myPOSTResponse,

Putting all that together:

$("#table_offerte").DataTable({
  paging: false,
  info: false,
  data: myPOSTResponse,
  columns: [
    { visible: false },  //this is the ID you don't want to see, no need to give it a title
    { title: "Nome e Cognome", className: "mdl-data-table__cell--non-numeric" },
    { title: "Tariffa Esterno" },
    { title: "Tariffa Interno" },
    { title: "Tariffa Viaggio" },
    { visible: false },  
    { visible: false },  
    { visible: false },  
    { title: "Attivo?" },
    { title: "RS?" },
    { title: "Iniziali", className: "mdl-data-table__cell--non-numeric" }
  ]
});

That should get you running, if you haven't done something else interesting. :)

Edit: as DocCobra mentions in the comments, you also have to specify the data: option here, since the array elements are objects. If they are themselves arrays, you do not.

这篇关于我无法设法将这个JSON数据放入DataTable中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆