[英]How to call php methods from js?
我正在研究櫃台服務項目,我需要控制客戶的流量,每個客戶可以在櫃台有5分鍾。 另一方面,系統應控制5個計數器。
這是我嘗試解決問題的方法。 看看我的MWE:
//this is part of the code where I set the timer for each counter. function increment() { if (running == 1) { setTimeout(function() { time++; var mins = Math.floor(time / 10 / 60); var secs = Math.floor(time / 10); var tenths = time % 10; if (mins == 5) { //after 5 mins is over the system should call php deQueue() method to dequeue the current and point out to next customer. document.getElementById("message").innerHTML = "Currently, Counters are available... Next Customer..." deQueue(); //this is my php method. available(); } document.getElementById("timer").innerHTML = mins + ":" + secs + ":" + tenths; increment(); }, 100) } }
//And this is my php file. <?php public function deQueue(){ if (!$this->isEmpty()) { $this->front = ($this->front+1) %5; $this->size--; }else{ echo "The Counter is empty! <br>"; } } ?>
現在你需要對你的php文件使用ajax請求,如下所示:
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
if (mins == 5) ajaxDequeue(mins);
document.getElementById("timer").innerHTML = mins + ":" + secs + ":" + tenths;
increment();
}, 100)
}
}
function ajaxDequeue(mins){
$.ajax({
url: 'ajax.php?minutes=' + mins,
beforeSend: function()
{
document.getElementById("message").innerHTML = "Currently, Counters are available... Next Customer..."
},
success: function(response)
{
document.getElementById("message").innerHTML = response;
}
});
}
然后在你的ajax.php文件中設置它以檢查分鍾值
<?php
$minutes = $_GET["minutes"];
if (isset($minutes)) deQueue();
public function deQueue(){
if (!$this->isEmpty()) {
$this->front = ($this->front+1) %5;
$this->size--;
}else{
echo "The Counter is empty! <br>";
}
}
?>
對我來說,你似乎試圖直接從JavaScript調用PHP函數。 用簡單的詞來形容它,這兩種語言通常需要一個額外的層來進行通信,稱為HTTP ,因為PHP在Web服務器上運行,JavaScript在webbrowser上運行。
要在“一段時間后”執行JavaScript函數,您可以使用setTimeout 。
要打開與PHP(webserver)的通信,您可以使用AJAX 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.