首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从js调用php方法?

问如何从js调用php方法?
EN

Stack Overflow用户
提问于 2019-03-23 11:26:03
回答 2查看 64关注 0票数 3

我正在从事柜台服务项目,我需要控制客户的流量,每个客户可以有5分钟在柜台。另一方面,系统应控制5个计数器。

这是我尝试解决这个问题的方法。看看我的MWE:

​

代码语言:javascript
复制
 //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)
      }
}
代码语言:javascript
复制
//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>";
    		}
    	}
    
    ?>

​

EN

回答 2

Stack Overflow用户

发布于 2019-03-23 12:14:45

现在您需要对php文件使用ajax请求,如下所示:

代码语言:javascript
复制
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文件中将其设置为检查分钟值

代码语言:javascript
复制
<?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>";
            }
        }
?>
票数 2
EN

Stack Overflow用户

发布于 2019-03-23 11:49:15

在我看来,您正在尝试直接从JavaScript调用PHP函数。为了用简单的话来描述,这两种语言通常需要一个额外的层来通信,称为HTTP,因为PHP运行在and服务器上,而JavaScript运行在and浏览器上。

要“在一段时间后”执行JavaScript函数,可以使用setTimeout。

要打开与PHP (webserver)的通信,您可以使用AJAX。

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

https://stackoverflow.com/questions/55310336

复制
相关文章

相似问题

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