首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在更新数据库中表中的特定字段后使用ajax自动更新页面?

如何在更新数据库中表中的特定字段后使用ajax自动更新页面?
EN

Stack Overflow用户
提问于 2021-11-20 17:51:40
回答 2查看 796关注 0票数 1

我正在编写一个餐馆应用程序,客户可以在网页上订购食物。我遇到的问题是,当顾客订购食物时,网络会输出订单尚未支付的情况,直到顾客将订单支付给餐厅员工,餐厅工作人员才能从另一个设备更新数据库中的订单。我希望这个网页能够不断地用相同的"order_id“检查数据库,并检查"status”字段。status字段将具有整数值(0=havent paid,1=paid) --这是排序的工作方式。

  • 这家伙从盖伊的设备上订购食物
  • 那家伙点击“完成”
  • 这个顺序被放置在一个表数据库中,它的字段集就像这样("order_id","order_status")
  • 盖伊的网页输出“等待付款”
  • 他把钱给了员工
  • 工作人员从另一个设备将"order_status“从0更新到1
  • 盖伊的网页自动输出“收到的付款”,并显示返回到home.php的按钮

这是我的网页

代码语言:javascript
复制
<div class="modal-header">
  <h5 class="modal-title" id="">Waiting for payment</h5>
  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
  <p class="h5">Transaction is on going <span class='spinner-border spinner-border-sm'></span></p>
  <p class='h5'>total price = Rp. <?php echo $_SESSION['totalprice'];?> ,-</p>
  <div class="overflow-auto mb-3" style="height: 400px;">
  </div>
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">cancel</button>
</div>

我计划在这个项目中使用ajax,但我对ajax非常陌生,而另一个线程似乎并不完全符合我的要求,因为它涉及到按钮单击或用户的输入,但我希望这是实时的,没有来自客户的任何输入。我使用mysql作为数据库。

EN

回答 2

Stack Overflow用户

发布于 2021-11-20 18:01:59

您的AJAX调用可以使用Javascript的恰当命名的setInterval()函数以设定的间隔进行。

在窗口和工作者接口上提供的setInterval()方法,会重复调用函数或执行代码段,每次调用之间都会有固定的时间延迟。 此方法返回唯一标识间隔的间隔ID,因此以后可以通过调用clearInterval()来删除它。

MDN setInterval()

票数 0
EN

Stack Overflow用户

发布于 2021-11-20 23:28:29

好吧,你会遇到这样的事情

代码语言:javascript
复制
<script>
function checkOrderStatus(){
     // Instantiate an new XHR Object
        const xhr = new XMLHttpRequest();
  
        // we call the file responsible for checking the db
        xhr.open("GET","check_order.php", true);
  
        // When response is ready
        xhr.onload = function () {
            if (this.status === 200) {  
                // we check the data return 
                if(this.responseText === 1){
                    // Getting the element where we will display our response message
                let feedback = getElementsByClassName("h5");
                feedback.innerHTML = "Payment Received";
                clearInterval(timer); // we stop checking the database
                 } else {
                    console.log('Still waiting...');
               };              
                
            }
            else {
                console.log("Something went wrong!");
            }
        }
  
        // At last send the request
        xhr.send();
    }
}

// now we want call this function every 3 seconds
let timer = setInterval(() => checkOrderStatus(), 3000);

当然,您必须将订单ID附加到check_order.php的url或作为会话变量传递。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70048452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档