如何使用ajax和php将数据从数据库表放入html表
我想做的是使用ajax和php将我的数据库表数据放到我的索引页面中的html表中。
我的问题是数据没有显示。 有谁知道我的代码有什么问题?
HTML:
Name Age Gender Action
脚本:
$(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 = $(" "); $(" ").text(record.name).appendTo(row); $(" ").text(record.age).appendTo(row); $(" ").text(record.gender).appendTo(row); $(" ").text(record.action).appendTo(row); row.appendTo('myTable2'); } }) } } }); $('#myTable2').dataTable({ "bjQueryUI": true, "sPaginationType": "full_numbers" }); });
process.php
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 tbody').append(row);
正如保罗所说,你的选择是错误的
- hash是id
$('#myTable')
- 句点(。)用于类
$('.redTable')
- 元素(a,li,table)没有前缀
$('table')
- 更高级的属性选择器
$(['href="importantLink.html"'])
检查并确保PHP为您的脚本提供了一个好的对象。 确保使用正确的选择器找到DOM元素。
$('#myTable2').find('tbody').append(row);
是你在找什么