Javascript 如何从.js脚本事件触发PHP函数?

Javascript 如何从.js脚本事件触发PHP函数?,javascript,php,jquery,function,eventtrigger,Javascript,Php,Jquery,Function,Eventtrigger,我正在写一个在网络浏览器中运行的游戏应用程序。到目前为止,我几乎所有的东西都是用PHP和HTML/CSS编写的。我当前的目标是在运行某个Javascript事件时触发PHP函数。确切地说,当demo.JS中的(JS)currentTime达到0时,我想将一个php bool设置为true,或者直接从class.game.php触发一个php函数 这是index.php文件的一部分,我在其中实现了timer元素 你好 我正在写一个在网络浏览器中运行的游戏应用程序。到目前为止,我几乎所有的东西都是用

我正在写一个在网络浏览器中运行的游戏应用程序。到目前为止,我几乎所有的东西都是用PHP和HTML/CSS编写的。我当前的目标是在运行某个Javascript事件时触发PHP函数。确切地说,当demo.JS中的(JS)currentTime达到0时,我想将一个php bool设置为true,或者直接从class.game.php触发一个php函数

这是index.php文件的一部分,我在其中实现了timer元素

你好

我正在写一个在网络浏览器中运行的游戏应用程序。到目前为止,我几乎所有的东西都是用PHP和HTML/CSS编写的。我当前的目标是在运行某个JS事件时触发PHP函数。确切地说,当demo.JS中的(JS)currentTime达到0时,我想将一个php bool设置为true,或者直接从class.game.php触发一个php函数。下面我将向您展示部分代码

其中包括:

index.php

<script type="text/javascript" src="inc/jquery.min1.js"></script>
<script type="text/javascript" src="inc/jquery.timer.js"></script>
<script type="text/javascript" src="inc/demo.js"></script>
<div id="countdown" style="float: right; margin-top: 60px; margin-right: 30px">01:00:00 </div>

    <form id="example2form" style="float: right; margin-top: 25px;">
        <input type='button' value='Play/Pause' onclick='Example2.Timer.toggle();' />
        <input type='button' value='Stop/Reset' onclick='Example2.resetCountdown();' />
        <input type='text' name='startTime' value='300' style='width:30px;' />
    </form>
/**
    * Purpose: end the game
    * Preconditions: turns on the game over flag
    * Postconditions: game over flag is true
    **/
    function end()
    {
        $this->over = true;
    }

/**
    * Purpose: return bool to indiciate whether or not the game is over
    * Preconditions: none
    * Postconditions: returns true or flase
    **/
    function isOver()
        {
            if ($this->won)
                return true;

            if ($this->over)
                return true;

            if ($this->health < 0) 
                return true;

            return false;
        }
if(isset($_GET["isTimerComplete"])==true)
{
    // Do additional sanitizations here,
    // e.g. http://www.w3schools.com/php/php_form_validation.asp
    $isTimerComplete=$_GET["isTimerComplete"];
    if($isTimerComplete){
        echo "success";
        yourFunction(); // function that set an php bool to true
    }
}
部分 class.game.php

<script type="text/javascript" src="inc/jquery.min1.js"></script>
<script type="text/javascript" src="inc/jquery.timer.js"></script>
<script type="text/javascript" src="inc/demo.js"></script>
<div id="countdown" style="float: right; margin-top: 60px; margin-right: 30px">01:00:00 </div>

    <form id="example2form" style="float: right; margin-top: 25px;">
        <input type='button' value='Play/Pause' onclick='Example2.Timer.toggle();' />
        <input type='button' value='Stop/Reset' onclick='Example2.resetCountdown();' />
        <input type='text' name='startTime' value='300' style='width:30px;' />
    </form>
/**
    * Purpose: end the game
    * Preconditions: turns on the game over flag
    * Postconditions: game over flag is true
    **/
    function end()
    {
        $this->over = true;
    }

/**
    * Purpose: return bool to indiciate whether or not the game is over
    * Preconditions: none
    * Postconditions: returns true or flase
    **/
    function isOver()
        {
            if ($this->won)
                return true;

            if ($this->over)
                return true;

            if ($this->health < 0) 
                return true;

            return false;
        }
if(isset($_GET["isTimerComplete"])==true)
{
    // Do additional sanitizations here,
    // e.g. http://www.w3schools.com/php/php_form_validation.asp
    $isTimerComplete=$_GET["isTimerComplete"];
    if($isTimerComplete){
        echo "success";
        yourFunction(); // function that set an php bool to true
    }
}
/**
*目的:结束游戏
*先决条件:打开游戏结束标志
*后置条件:游戏结束旗帜是正确的
**/
函数结束()
{
$this->over=true;
}
/**
*目的:返回布尔值以指示游戏是否结束
*先决条件:无
*后置条件:返回true或flase
**/
函数isOver()
{
如果($this->win)
返回true;
如果($this->over)
返回true;
如果($this->health<0)
返回true;
返回false;
}
什么时候

timerComplete()

是在demo.js中触发的,我想触发函数

完()


在class.game.php中,如何实现这一点

这里是一个快速的AJAX示例

demo.js

/**
 * countdown function
 */
var Example2 = new (function() {
    var $countdown,
        $form, // Form used to change the countdown time
        incrementTime = 70,
        currentTime = 1000,
        updateTimer = function() {
            $countdown.html(formatTime(currentTime));
            if (currentTime == 0) {
                Example2.Timer.stop();
                timerComplete();
                Example2.resetCountdown();


                return;
            }
            currentTime -= incrementTime / 10;
            if (currentTime < 0) currentTime = 0;
        },
        timerComplete = function() {
            alert('Example 2: Countdown timer complete!');

        },
        init = function() {
            $countdown = $('#countdown');
            Example2.Timer = $.timer(updateTimer, incrementTime, true);
            $form = $('#example2form');
            $form.bind('submit', function() {
                Example2.resetCountdown();
                return false;
            });
        };
    this.resetCountdown = function() {
        var newTime = parseInt($form.find('input[type=text]').val()) * 100;
        if (newTime > 0) {currentTime = newTime;}
        this.Timer.stop().once();
    };
    $(init);
});
;(function($) {
    $.timer = function(func, time, autostart) { 
        this.set = function(func, time, autostart) {
            this.init = true;
            if(typeof func == 'object') {
                var paramList = ['autostart', 'time'];
                for(var arg in paramList) {if(func[paramList[arg]] != undefined) {eval(paramList[arg] + " = func[paramList[arg]]");}};
                func = func.action;
            }
            if(typeof func == 'function') {this.action = func;}
            if(!isNaN(time)) {this.intervalTime = time;}
            if(autostart && !this.isActive) {
                this.isActive = true;
                this.setTimer();
            }
            return this;
        };
        this.once = function(time) {
            var timer = this;
            if(isNaN(time)) {time = 0;}
            window.setTimeout(function() {timer.action();}, time);
            return this;
        };
        this.play = function(reset) {
            if(!this.isActive) {
                if(reset) {this.setTimer();}
                else {this.setTimer(this.remaining);}
                this.isActive = true;
            }
            return this;
        };
        this.pause = function() {
            if(this.isActive) {
                this.isActive = false;
                this.remaining -= new Date() - this.last;
                this.clearTimer();
            }
            return this;
        };
        this.stop = function() {
            this.isActive = false;
            this.remaining = this.intervalTime;
            this.clearTimer();
            return this;
        };
        this.toggle = function(reset) {
            if(this.isActive) {this.pause();}
            else if(reset) {this.play(true);}
            else {this.play();}
            return this;
        };
        this.reset = function() {
            this.isActive = false;
            this.play(true);
            return this;
        };
        this.clearTimer = function() {
            window.clearTimeout(this.timeoutObject);
        };
        this.setTimer = function(time) {
            var timer = this;
            if(typeof this.action != 'function') {return;}
            if(isNaN(time)) {time = this.intervalTime;}
            this.remaining = time;
            this.last = new Date();
            this.clearTimer();
            this.timeoutObject = window.setTimeout(function() {timer.go();}, time);
        };
        this.go = function() {
            if(this.isActive) {
                this.action();
                this.setTimer();
            }
        };

        if(this.init) {
            return new $.timer(func, time, autostart);
        } else {
            this.set(func, time, autostart);
            return this;
        }
    };
})(jQuery);
timerComplete = function() {
    alert('Example 2: Countdown timer complete!');
    sendAjax();
}

function sendAjax()
{
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      if(xmlhttp.responseText.match("success")){
          alert("AJAX returns success");
      }else{
          // something bad heppened
      }
    }
  }
  xmlhttp.open("GET","class.game.php?isTimerComplete=1",true);
  xmlhttp.send();
}    
class.game.php

<script type="text/javascript" src="inc/jquery.min1.js"></script>
<script type="text/javascript" src="inc/jquery.timer.js"></script>
<script type="text/javascript" src="inc/demo.js"></script>
<div id="countdown" style="float: right; margin-top: 60px; margin-right: 30px">01:00:00 </div>

    <form id="example2form" style="float: right; margin-top: 25px;">
        <input type='button' value='Play/Pause' onclick='Example2.Timer.toggle();' />
        <input type='button' value='Stop/Reset' onclick='Example2.resetCountdown();' />
        <input type='text' name='startTime' value='300' style='width:30px;' />
    </form>
/**
    * Purpose: end the game
    * Preconditions: turns on the game over flag
    * Postconditions: game over flag is true
    **/
    function end()
    {
        $this->over = true;
    }

/**
    * Purpose: return bool to indiciate whether or not the game is over
    * Preconditions: none
    * Postconditions: returns true or flase
    **/
    function isOver()
        {
            if ($this->won)
                return true;

            if ($this->over)
                return true;

            if ($this->health < 0) 
                return true;

            return false;
        }
if(isset($_GET["isTimerComplete"])==true)
{
    // Do additional sanitizations here,
    // e.g. http://www.w3schools.com/php/php_form_validation.asp
    $isTimerComplete=$_GET["isTimerComplete"];
    if($isTimerComplete){
        echo "success";
        yourFunction(); // function that set an php bool to true
    }
}

请访问类似的网站


或者通过谷歌搜索类似“Ajax php示例”的内容来了解更多关于Ajax及其如何与php文件交互的信息。

为了补充@user2875289的答案,如果您的网页上已经有jquery,为什么不使用它,只需使用javascript即可:

timerComplete = function() {
    alert('Example 2: Countdown timer complete!');
    callPHPMethod("class.game.php?isTimerComplete=1", function(returnedPHPfunctionValue){
         // it was success, now you can do something with returnedPHPfunctionValue
    });
}

function callPHPMethod(method, callback)
{
  $.ajax({
        url: method,
        method: "GET",
        success: function(data){
              if($.isFunction(callback)) callback(data)
        },
        error: function(){
              //do something with error
        }
  });
在您的PHP中,按照@user2875289的指示执行:

if(isset($_SESSION["isTimerComplete"]) != true)
{
    // Do additional sanitizations here
    $isTimerComplete=$_GET["isTimerComplete"];
    //
    if($isTimerComplete){
        echo "success";
        yourPHPFunction(); // function that set an php bool to true
    }
}

你需要了解AJAX。你在寻找AJAX请求吗?我以前从未使用过AJAX,对于这个解决方案,实现AJAX的实用方法是什么?非常感谢,我现在就来试试