【问题标题】:How to call php methods from js?如何从js调用php方法?
【发布时间】:2019-08-14 01:45:21
【问题描述】:

我正在从事柜台服务项目,我需要控制客户的流量,每个客户可以在柜台停留 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>";
    		}
    	}
    
    ?>

【问题讨论】:

  • 您添加 ajax 标签的任何原因?

标签: javascript php arrays ajax queue


【解决方案1】:

现在您需要对 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>";
            }
        }
?>

【讨论】:

    【解决方案2】:

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

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

    要打开与 PHP(网络服务器)的通信,您可以使用 AJAX

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      相关资源
      最近更新 更多