javascript - 如何使用ajax和php将数据库表中的数据放入html表

标签 javascript php jquery html ajax

我想做的是使用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>

流程.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);

关于javascript - 如何使用ajax和php将数据库表中的数据放入html表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25047156/

相关文章:

php - 如何通过 PHP 中的循环获取表单值

php - 如何在mysql中使用like条件与更多单词

jquery - 无法使用 casperjs 找到现有元素

javascript - 在可折叠 jquery-mobile 中添加动态可过滤控制组

jquery - HTML 超链接保持在同一位置

javascript - 制作双语静态简单 HTML 网站的最佳方法是什么?

javascript - 找不到创建多个历史条目的 popstate 循环的位置

javascript - 使用 jquery 验证条件时显示警报

javascript - Node 脚本不会通过 https 运行

php:不知从何而来的空行