繁体   English   中英

如何从js调用php方法?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM