为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
万千封印 2021-10-15 14:43:55
我已经分解了我的问题以提供一个没有开销的简洁示例。然而足以给你一个想法。我有一个简单的 index.php<?php    include 'myClass.php';?><html><head></head><body>    <div> <?php myClass->printTable(); ?> </div></body></html>该函数返回一个完整的表,其中填充了后端正在准备的数据。<?phpfunction 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 完成的。但我不明白该怎么做。我查找了不同的资源,尽管在这种方法中它们实际上都不够具体。
查看完整描述

2 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

我正在寻找广泛或非特定的方式来从后端获取一些数据并将其显示在我页面上的 div 中。


解决方案是创建一个单独的 PHP (fetch.php) 文件,该文件仅回显我需要在 div 中显示的数据


从包含我的 div 的页面中,我会执行以下操作:


<div id="result"></div>


<script>


function load_data()

{

    $.ajax({

        url:"fetch.php",

        method:"POST",

        success:function(data)

        {

            $('#result').html(data);

        }

    });

}


load_data()


</script>


在 fetch.php 中,我可以做任何我想做的事情,包括查询我的数据库并将值存储在一个变量中,该变量将在最后回显。来自 fetch.php 的这个响应(回显)将显示在我的 div 中。同样,我也可以在 ajax 函数中指定一个 .txt (url:"sometext.txt") .txt 的内容也可以这样显示在我的 div 中。我对它是如何工作的缺乏了解使得它真的很难理解。


此外,我添加了一个功能来每秒刷新内容(或响应)。如果我从 fetch.php 中回显 time() 它将自动增加而不会在我的 div 中重新加载页面


setInterval(function(){

    load_data()

}, 1000);


查看完整回答
反对 回复 2021-10-15
  • 2 回答
  • 0 关注
  • 153 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号