简体   繁体   English

使用jQuery .post()无法使DataTable工作

[英]Can't make DataTables work by using jQuery .post()

I am working on a form where a uses chooses a date range in order to display information by using DataTables. 我正在使用一个表单,其中一个用户选择一个日期范围,以便使用DataTables显示信息。

When the user clicks on the button, the dates are sent through jQuery .post() function and it retrieves the info as expected. 当用户单击该按钮时,日期将通过jQuery .post()函数发送,并按预期检索信息。

Here is the piece of the code related to it: 这是与之相关的代码片段:

//Sending the dates range
$.post(url_route, datos, function(data,status){
    if(status=='success'){
       var response = jQuery.parseJSON(data);
       //checking if data were found
       if(response.list_events.length === 0){
          console.log('No data available');
       }
       else{
         //Let us display the info with DataTables inside div #list_events and 
         //table #table_id
         $('#list_events').html('<table class="table table-striped table-hover" id="table_id"></table>');
         $('#list_events table').append('<thead><tr><th>Event</th><th>Type</th><th>Attendance</th><th>Coordinators</th><th>Participants</th><th>Institutes</th><th>Talks</th></tr></thead><tbody></tbody>');
         //retrieving the info for each row and append it to the table:
         $.each(response.list_events,function(i,item)
         {
           $('#list_events').find('tbody').append('<tr>');
           $('#list_events').find('tbody').append('<td>'+item.Event+'</td>');
           $('#list_events').find('tbody').append('<td>'+item.Type+'</td>');
            $('#list_events').find('tbody').append('<td>'+item.Attendance+'</td>');
          $('#list_events').find('tbody').append('<td>'+item.Coordinator+'</td>');
          $('#list_events').find('tbody').append('<td>'+item.Participant+'</td>');
           $('#list_events').find('tbody').append('<td>'+item.Institute+'</td>');
           $('#list_events').find('tbody').append('<td>'+item.Talk+'</td>');
        });//end of each

        //initializing DataTables
        var table = $('#table_id').DataTable(); 

       }//end of else (info found)
    }//end of if success
}//end of post()

So far, the info is displayed in the DataTables but it is not totally working, since only the information is displayed. 到目前为止,信息显示在DataTables中,但它并不完全有效,因为只显示信息。 The DataTables search, next, and previous buttons, as well as the number of results dropdown menu are not shown. 不显示DataTables搜索,下一个和上一个按钮,以及结果下拉菜单的数量。

In the console.log I get the following error: 在console.log中我收到以下错误:

Uncaught TypeError: Cannot read property 'length' of undefined 未捕获的TypeError:无法读取未定义的属性“长度”

Any ideas? 有任何想法吗? Can anyone shed some light on this? 任何人都可以对此有所了解吗?

Solved 解决了

The problem was with the append function. 问题出在附加功能上。 If I type just one append with only the <tr> like this: 如果我只输入一个附加只有<tr>附加内容:

$('#list_events').find('tbody').append('<tr>');

The result in HTML is <tr></tr> That is to say, the tag is closed automatically ... no matter what. HTML中的结果是<tr></tr>也就是说,标签会自动关闭......无论如何。 So, the solution was to put all the appends in one line like the following: 所以,解决办法是把所有的附加在类似下面一行

$('#list_events').find('tbody').append('<tr><td>'+item.Event+'</td><td>'+item.Type+'</td><td>'+item.Attendance+'</td><td>'+item.Coordinator+'</td><td>'+item.Participant+'</td><td>'+item.Institute+'</td><td>'+item.Talk+'</td></tr>');

And that was it ☺ 那就是它

My first thought is that perhaps "response.list_events" is undefined. 我的第一个想法是,也许“response.list_events”未定义。 Certainly your error: 当然是你的错误:

"Uncaught TypeError: Cannot read property 'length' of undefined" “未捕获的TypeError:无法读取未定义的属性'长度'”

seems to imply that. 似乎暗示了这一点。

My second thought is that I have recently done something similar where I had trouble with the .post method, and found success with the .ajax method. 我的第二个想法是,我最近做了类似的事情,我遇到了.post方法的问题,并且发现了.ajax方法的成功。
Try something along these lines: 尝试这些方面的东西:

$.ajax({
    type: "POST",
    url: url_route,
    data: datos,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(returned_from_server){
         // your function here
    }
});

My third thought is that I don't see where you put your closing row tags. 我的第三个想法是,我没有看到你把结束行标记放在哪里。

$.each(response.list_events,function(i,item)
     {
      $('#list_events').find('tbody').append('<tr>');
      $('#list_events').find('tbody').append('<td>'+item.Event+'</td>');
      $('#list_events').find('tbody').append('<td>'+item.Type+'</td>');
      $('#list_events').find('tbody').append('<td>'+item.Attendance+'</td>');
      $('#list_events').find('tbody').append('<td>'+item.Coordinator+'</td>');
      $('#list_events').find('tbody').append('<td>'+item.Participant+'</td>');
      $('#list_events').find('tbody').append('<td>'+item.Institute+'</td>');
      $('#list_events').find('tbody').append('<td>'+item.Talk+'</td>');
      $('#list_events').find('tbody').append('</tr>');  // <--- I believe you might be missing this!!
    });//end of each 

Hopefully this was some help. 希望这是一些帮助。

If you are using a remote source for your data, it is far more elegant and efficient to let DataTables itself render the data for you. 如果您正在为数据使用远程源,那么让DataTables本身为您呈现数据会更加优雅和高效。

In your example, you fetch the data, build the table, and then turn it into a "DataTable". 在您的示例中,您获取数据,构建表,然后将其转换为“DataTable”。 If it meets the requirements and gets the job done, you've written perfectly fine code and you should read this answer no more! 如果它符合要求并完成工作,那么你已经编写了完美的代码,你应该不再阅读这个答案!

But DataTables itself is awfully smart about rendering data detached from the DOM and then slotting it all in place. 但DataTables本身非常聪明地将数据从DOM中分离出来,然后将其全部插入到位。 You get the benefit of more efficient updates while simultaneously having cleaner code. 您可以获得更高效的更新,同时拥有更清晰的代码。

Here's a basic example. 这是一个基本的例子。 Without testing it in your environment, I can't say for sure it will do your job, but I think it should: 如果不在您的环境中测试它,我不能肯定它会完成您的工作,但我认为它应该:

var myTable = $('#table_id').DataTable( {
  "ajax": {
    "url": url_route,
    "data": function(customData) {
      customData.datos = datos // need some way to have access to datos
    }
  }
});

And then on click, if you want to retrieve newer data based on whatever has changed (the date range?) you just have to redraw. 然后单击,如果要根据已更改的内容(日期范围?)检索更新的数据,则只需重新绘制。

myTable.draw();

I can imagine a few ways to get datos in there-- wrap it up in a function that accepts and uses datos. 我可以设想一些方法来获取数据 - 将其包含在一个接受和使用数据的函数中。 Declare a namespaced or otherwise quasi-global (or actually global if you're that guy!) variable that myTable would have access to at any given point in time... or even just destroy the current table and call the whole DataTable() on it again. 声明一个命名空间或其他准全局(或者实际上是全局的,如果你是那个人!)变量,myTable可以在任何给定的时间点访问...甚至只是破坏当前表并调用整个DataTable()再次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM