jquery ajax和datatables有问题

时间:2012-04-06 12:51:51

标签: javascript jquery datatables

我正在尝试使用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>

2 个答案:

答案 0 :(得分: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”来调用应用dataTables的函数。变化:

$.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();
});

答案 1 :(得分:0)

你应该将.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中尚不存在的表