2012-04-06 83 views
1

我想用jquery ajax從php文件中獲取數據。這個php文件打印出一個由db查詢製成的表格。一旦表格返回到html頁面,我想將數據表樣式應用於表格,但這不起作用。jquery ajax和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> 
+1

一些代碼,看看可以幫助 – fcalderan 2012-04-06 12:53:06

+0

請張貼一些代碼 – nandu 2012-04-06 12:54:56

+0

我已經加入到我的答案,你發佈的代碼。 – psynnott 2012-04-06 13:05:34

回答

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

編輯因您的更新

您需要更改「事件偵聽器的點擊次數」來稱呼你的函數應用於數據表。變化:

$.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

它工作!令人驚訝的是,一直在爲此奮鬥了幾天。謝謝一堆。 – 2012-04-06 13:09:58

+0

不用擔心。你也可以重構你的代碼來刪除代碼重複:) – psynnott 2012-04-06 13:11:41

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() 
    } 

否則你試圖TRANSFORMA表不會在DOM

+0

注意,要將dataTables應用到表中,它是$('#tableID')。dataTable()(no's')。 – psynnott 2012-04-06 13:03:07