猿问

如何ajaxify一个在后端执行SQL的PHP​​函数?

我已经分解了我的问题以提供一个没有开销的简洁示例。然而足以给你一个想法。


我有一个简单的 index.php


<?php

    include 'myClass.php';

?>


<html>

<head></head>

<body>

    <div> <?php myClass->printTable(); ?> </div>

</body>

</html>

该函数返回一个完整的表,其中填充了后端正在准备的数据。


<?php


function printTable()

{        

    // printing static table header

    echo '    <table class="table" style="zoom: 0.75;">

                <thead class="thead-dark">

                    <tr>

                        <th scope="col">Date</th>           // current date

                        <th scope="col">Order Number</th>   // an int

                        <th scope="col">Current Value</th>  // an int

                    </tr>

                </thead>

                <tbody>

        ';


    $result = mysqli_query($this->link, "SELECT * FROM `someData`");

    while ($row = mysqli_fetch_assoc($result))

    {   

        $orderNumber = $row['orderNumber'];

        $currentValue = $row['currentValue'];

        $date = $this->getDate($orderNumber);   // member function that returns a timestamp from the database


        //printing actual table

        echo '      <tr>

                        <td>'. $date .'</td>

                        <td>'. $orderNumber .'</td>

                        <td>'. $currentValue .'</td>

                    </tr>

            ';

    }


echo '       </tbody>

        </table>

    ';      

}


?>

我从数据库中查询的数据在不断变化。我想要前端的“实时”视图。我知道这是通过使用 Ajax 完成的。但我不明白该怎么做。我查找了不同的资源,尽管在这种方法中它们实际上都不够具体。


万千封印
浏览 154回答 2
2回答

慕田峪7331174

我正在寻找广泛或非特定的方式来从后端获取一些数据并将其显示在我页面上的 div 中。解决方案是创建一个单独的 PHP (fetch.php) 文件,该文件仅回显我需要在 div 中显示的数据从包含我的 div 的页面中,我会执行以下操作:<div id="result"></div><script>function load_data(){&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; url:"fetch.php",&nbsp; &nbsp; &nbsp; &nbsp; method:"POST",&nbsp; &nbsp; &nbsp; &nbsp; success:function(data)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#result').html(data);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });}load_data()</script>在 fetch.php 中,我可以做任何我想做的事情,包括查询我的数据库并将值存储在一个变量中,该变量将在最后回显。来自 fetch.php 的这个响应(回显)将显示在我的 div 中。同样,我也可以在 ajax 函数中指定一个 .txt (url:"sometext.txt") .txt 的内容也可以这样显示在我的 div 中。我对它是如何工作的缺乏了解使得它真的很难理解。此外,我添加了一个功能来每秒刷新内容(或响应)。如果我从 fetch.php 中回显 time() 它将自动增加而不会在我的 div 中重新加载页面setInterval(function(){&nbsp; &nbsp; load_data()}, 1000);
随时随地看视频慕课网APP
我要回答