如何使用ajax和php将数据从数据库表放入html表 [英] How to put data from database table to a html table using ajax and php

查看:65
本文介绍了如何使用ajax和php将数据从数据库表放入html表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是使用ajax和php将我的数据库表数据放到索引页面的html表中。

I want to do is put my database table data to html table in my index page using ajax and php.

我的问题是数据没有显示。有谁知道我的代码有什么问题?

My problem is the data is not showing. Does anyone know whats the problem with my code?

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

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> 标签。

since you're looking for id=myTable2, not a <myTable2> tag.

尽管如Theodore的评论所述,你真的想要:

Though, as noted in Theodore's comment, you really want:

$('#myTable2 tbody').append(row);

这篇关于如何使用ajax和php将数据从数据库表放入html表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆