【问题标题】:Display the MySQL table using PHP and JavaScript in datatable在数据表中使用 PHP 和 JavaScript 显示 MySQL 表
【发布时间】:2019-03-19 17:07:55
【问题描述】:

目前,我正在开发一个网站以扩展和提高我在 Web 开发方面的知识,我是编程初学者。

所以我试图在 html 数据表中显示名为accountinfo 的表的数据。我尝试使用php 仅在 html 数据表中显示它,并在 html 文件中回显它,它工作得非常好。像这样:

<table id="tblList" class="text-center">
    <thead class="bg-light text-capitalize">
        <tr>
            <th hidden>User ID</th>
            <th>Control No.</th>
            <th>Account Name</th>
            <th>Date Inspection</th>
            <th>Date of Report</th>
            <th>Actual Use</th>
            <th>Landmark</th>
            <th>Registered Owner</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <?php
            echo $output;
        ?>
    </tbody>
</table>

此代码没有错误,但我想使用 javascript 将其显示在数据表中。

但我不知道如何处理它..

我已经尝试了一点,但我没有得到正确的结果。它不会在 HTML 数据表中显示 Mysql 表的值。

我试过这个:

function loadAccountList() {
    $.ajax({
        type: 'POST',
        url: '../php_functions/tableList.php',
        dataType: 'json',
        data: xdata,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            $('#tbodyemplist').empty();
            var cells = eval("(" + response.d + ")");
            for (var i = 0; i < cells.length; i++) {

                var resDate;
                if (cells[i].res_date == "")
                {
                    resDate = "N/A";
                }
                else
                {
                    resDate = cells[i].res_date;
                }

                $('#tbodyemplist').append('<tr data-empid="' + cells[i].ID + '">'
                + '<td style="font-size:11px; text-align:center;" hidden>' + cells[i].badgenum+ '</td>'
                + '<td style="font-size:11px; text-align:center;">' + cells[i].CN+ '</td>'
                + '<td style="font-size:11px; text-align:center;">' +cells[i].AccName+ '</td>'
                + '<td style="font-size:11px; text-align:center;">' + cells[i].DI+ '</td>'
                + '<td style="font-size:11px; text-align:center;">' +cells[i].contact_no+'</td>'
                + '<td style="font-size:11px; text-align:center;">' + cells[i].DR+</td>'
                + '<td style="font-size:11px; text-align:center;">' +  cells[i].ActUse+ '</td>'                            
                + '<td style="font-size:11px; text-align:center;">' + cells[i].Landmark+ '</td>'
                + '<td style="font-size:11px; text-align:center;">' + cells[i].status+ '</td>'
                                    + '</tr>');
            }
        },
        error: function (error) {
            console.log(error);
        },
        complete: function () {
            $('#tblemplist').dataTable({
                "order": [],
                "columnDefs": [{
                    "targets": 'no-sort',
                    "orderable": false,
                }]
            }).end();
            $('#tblemplist').css('width', '100%');
        }
    });
}

并像这样在html中调用它

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="jsFiles/index.js"></script>

还有php文件

<?php 
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "benchmark";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $acc_id="";
    $acc_name="";
    $date_inspection="";
    $date_report = "";
    $act_useof_prop="";
    $landmark="";
    $reg_owner="";
    $bvcsi_control = "";
    $status = "";
    $lstrow = "";

    $sql = "SELECT account_id, account_name, date_inspection, date_report, act_useof_prop, landmark, reg_owner, bvcsi_control,status from accountinfo ORDER BY account_id ASC";
    $result = mysqli_query($conn,$sql);
    $num = mysqli_num_rows($result);
    $output = '';
    if ($num > 0)
    {
        while ($row = mysqli_fetch_array($result))
        {
            $ID= $row["account_id"];
            $CN= $row["bvcsi_control"];
            $AccName= $row["account_name"];
            $DI= $row["date_inspection"];
            $DR= $row["date_report"];
            $actUse= $row["act_useof_prop"];
            $landmark = $row["landmark"];
            $reg_owner = $row["reg_owner"];
            $status = $row["status"];

        }
    }
?>

这个项目将交给我之前在职培训的公司。

编辑

请看附图:控制台错误:

enter image description here

编辑:enter image description here

【问题讨论】:

  • ajax 响应是什么,请将其添加到您的问题中。
  • 你的cosole有什么错误吗?
  • 这是我从jQuery官网上得到的“jqXHR.success()、jqXHR.error()和jqXHR.complete()回调方法从jQuery 3.0开始被移除。你可以使用jqXHR .done()、jqXHR.fail() 和 jqXHR.always() 代替。”您使用的是 3.3.1 版本。
  • 你能展示一下json数据是什么样子的吗?
  • 在这部分success: function (response) 尝试console.log(response) 它是在您的console 中显示数据(检查元素浏览器并选择控制台选项卡)?

标签: javascript php html


【解决方案1】:

如果您想使用 javascript 根据您的 database 创建表格,您需要的是:

第一步是,Select 数据到你的表并以json 格式返回。

比如这样,说成data.php:

$temparray = array();

$sqlselect = "SELECT * FROM accountinfo ";
$result = $conn->query($sqlselect);
if ($result->num_rows > 0){
    while($row = $result->fetch_assoc()) 
    {
        array_push($temparray, $row); //save your data into array
    }
}
echo json_encode($temparray);

尝试打开data.php 显示json数据?如果是,进入第二步。

第二步是,使用ajax调用你的json数据。

比如这样,说成loadTable.js:

$.ajax({
    url: "data.php",
    type: "get", 
    dataType: "JSON",
    data: {}, //this is data you send to your server
    success: function(res)
    {   
        console.log(res); //show all data
        console.log(res.length); //check data length

        //doing looping for create tbody.

    }
})

如果console.log显示数据,你可以使用循环进行下一步。

我尝试创建简单的工作示例来帮助您,希望对您有所帮助:

$.ajax({
  url: "https://api.myjson.com/bins/dgd5u", //change to your php file (in my example data.php)
  type: "get",
  dataType: "JSON",
  data: {}, //this is data you send to your server
  success: function(res) {
    console.log(res);
    console.log(res.length);

    for (let i = 0; i < res.length; i++) {
      $('#testing').append('<tr><td>' + res[i]['name'] + '</td><td>' + res[i]['phone'] + '</td><td>' + res[i]['email'] + '</td></tr>')
    }

  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<div class="col-md-6">
  <table class="table table-bordered" style="text-align:center">
    <thead>
      <td>Name</td>
      <td>Phone</td>
      <td>Email</td>
    </thead>
    <tbody id='testing'>
    </tbody>
  </table>
</div>

</div>

查看全文。

【讨论】:

  • 您好,先生!你的代码确实有效..但它有一个错误,它总是在数据表中显示no data available in table,并且数据表的搜索框不起作用。请再次查看附图。
  • 对于数据表插件,请确保您已经阅读了documentation how to load datatables using ajax。对于使用插件数据表,您不需要定义和附加它。我的示例基于您的实际操作,但从echo 方法更改为使用append。对于数据表,您需要不同的 ajax
  • 不同的ajax先生是什么意思??
  • 检查文档
  • 那么先生,为什么桌子看起来像这样??我的意思是。我做错了吗?
猜你喜欢
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
  • 1970-01-01
  • 2012-10-28
相关资源
最近更新 更多