[英]How to put data from database table to a html table using ajax and php
我想做的是使用ajax和php將數據庫表數據放入索引頁中的html表。
我的問題是數據沒有顯示。 有人知道我的代碼有什么問題嗎?
的HTML:
<table id="myTable2">
<thead>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Action</th>
</thead>
<tbody>
</tbody>
</table>
腳本:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'process.php',
type: 'post',
data: {tag: 'getData'},
dataType: 'json',
success: function(data){
if(data.success){
$.each(data, function(index, record){
if($.is_numeric(index)){
var row = $("<tr />");
$("<td />").text(record.name).appendTo(row);
$("<td />").text(record.age).appendTo(row);
$("<td />").text(record.gender).appendTo(row);
$("<td />").text(record.action).appendTo(row);
row.appendTo('myTable2');
}
})
}
}
});
$('#myTable2').dataTable({
"bjQueryUI": true,
"sPaginationType": "full_numbers"
});
});
</script>
process.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
if(isset($_POST['tag'])){
try{
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT name, age, gender, action FROM viewtables";
$result = $dbc->prepare($sql);
if(!$result->execute()) return false;
if($result->rowCount() > 0) {
$json = array();
while ($row = $result->fetch()){
$json[] = array(
'name' => $row['name'],
'age' => $row['age'],
'gender' => $row['gender'],
'action' => $row['action']
);
}
$json['success'] = true;
echo json_encode($json);
}
} catch (PDOException $e) {
echo "Error: " .$e->getMessage();
}
}
?>
至少,這是:
row.appendTo('myTable2');
需要是:
row.appendTo('#myTable2');
由於您要查找id=myTable2
,而不是<myTable2>
標記。
但是,正如西奧多(Theodore)的評論中所述,您確實想要:
$('#myTable2 tbody').append(row);
正如保羅所說,您的選擇器有誤
$('#myTable')
$('.redTable')
$('table')
前綴 $(['href="importantLink.html"'])
更高級 檢查並確保PHP正在為您的腳本重用一個好的對象。 確保使用正確的選擇器查找DOM元素。
$('#myTable2').find('tbody').append(row);
是您要尋找的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.