【问题标题】:Trouble with jquery ajax and datatablesjquery ajax 和数据表的问题
【发布时间】:2012-04-06 12:51:51
【问题描述】:

我正在尝试使用 jquery ajax 从 php 文件中获取数据。此 php 文件打印由 db 查询生成的表。一旦表格返回到 html 页面,我想将 datatables 样式应用于表格,但这不起作用。

也许我应该只使用数据表 ajax 功能,而不是 jquery ajax。我只有三个链接,用户可以单击它们来调用 ajax,其中并非所有链接都返回打印的表格。

我怀疑它是因为 javascript 计时,所有 js 在表格输出之前加载。

我尝试使用 jquery.on(),但无法让它与数据表一起使用。

感谢您的帮助。对不起,如果这令人困惑。

<script type="text/javascript">     
$(document).ready(function() {

// EVENT LISTENER FOR CLICKS
var option_action = "fridge";
var using = "pantry";
$.post("./backend.php", { option: option_action, action: using }, function(data) {
$("#content").html(data);
load_table();
});
// EVENT LISTENER FOR CLICKS
$(".pantry_menu li").click(function() {
    alert("CLICK");
//getting data from the html
var option_action = $( this ).attr("name");
var using = "pantry";
$.post("./backend.php", { option: option_action, action: using }, function(data) {      
    $("#content").html(data);
});
return false;
});

//Mouse action listeners for side bar
$(".pantry_menu li").mouseover(function() {
    $(this).css("border-bottom" , "2px solid black");
});
$(".pantry_menu li").mouseout(function() {
    $(this).css("border-bottom" , "2px dotted black");
});
$(".fridge_table1").change(function(){
   alert("CHANGE");
});
});

function load_table()
{
    $('.fridge_table1').dataTable( {
        "aaSorting": [[ 4, "desc" ]]
        ,"bJQueryUI": true
    });
}
</script>

【问题讨论】:

  • 我已在您发布代码时添加到我的答案中。

标签: javascript jquery datatables


【解决方案1】:

在您的 ajax 成功函数中,您可以将 dataTable 重新应用于表。例如:

  $.ajax({
    type: "POST",
    url: "ajax.php",
    data: {
      request: 'something'
    },
    async: false,
    success: function(output)
    {
      $('#myTableDiv').html(output); //the table is put on screen
      $('#myTable').dataTable();
    }
  });

因您的更新而编辑

您需要更改“EVENT LISTENER FOR CLICKS”来调用应用数据表的函数。变化:

$.post("./backend.php", { option: option_action, action: using }, function(data) {      
    $("#content").html(data);
});

$.post("./backend.php", { option: option_action, action: using }, function(data) {      
    $("#content").html(data);
    load_table();
});

【讨论】:

  • 成功了!太棒了,这几天一直在苦苦挣扎。非常感谢。
  • 不用担心。您还可以稍微重构您的代码以删除代码重复:)
【解决方案2】:

您应该将 .dataTables() 部分放在 ajax 函数的回调中

$.ajax{
    url: yoururl,
   ... 
    success: function(data){
        //append the table to the DOm
        $('#result').html(data.table)
        //call datatables on the new table
        $('#newtable').dataTables()
    }

否则,您正在尝试转换 DOM 中尚不存在的表

【讨论】:

  • 注意,要将dataTables应用到表中,是$('#tableID').dataTable()(没有's')。
猜你喜欢
  • 2011-06-20
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 2010-12-05
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-08-11
相关资源
最近更新 更多