我正在撰寫一個餐廳應用程式,客戶可以在其中在網頁上訂購食物。我遇到的問題是,當客戶完成訂購食物時,網路將輸出訂單尚未支付,直到客戶將其支付給餐廳員工并且餐廳員工從另一臺設備更新資料庫中的訂單。我希望這個網頁不斷檢查具有相同“order_id”的資料庫并檢查“狀態”欄位。狀態欄位將具有整數值(0=尚未支付,1=已支付)這就是排序的作業原理
- 家伙從家伙的設備訂購食物
- 家伙點擊“完成”
- 訂單被放置在一個帶有欄位集的表資料庫中,就像這樣(“order_id”,“order_status”)
- 小伙的網頁輸出“等待付款”
- 家伙付給作業人員
- 作業人員從另一臺設備將“order_status”從 0 更新為 1
- 家伙的網頁自動輸出“收到付款”并顯示一個按鈕回傳home.php
這是我的網頁
<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 作為資料庫。
uj5u.com熱心網友回復:
您可以使用 Javascript 恰當命名的setInterval()函式以設定的時間間隔進行 AJAX 呼叫。
Window 和 Worker 介面上提供的 setInterval() 方法重復呼叫函式或執行代碼片段,每次呼叫之間都有固定的時間延遲。
此方法回傳一個唯一標識間隔的間隔 ID,因此您可以稍后通過呼叫 clearInterval() 將其洗掉。
MDN setInterval()
uj5u.com熱心網友回復:
那么你將處理類似的事情
<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 或作為會話變數
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361813.html
標籤:javascript php html 查询 阿贾克斯
