连续查询数据库PHP


Continuously Query Database PHP

我需要每0.5秒查询一个数据库,看看某个字段是否为空。我已经在Java中工作了,但由于PHP没有线程,我不太确定如何去做。我已经看到了很多关于AJAX的东西,但我发现很难将它应用到我的情况,因为我以前从未使用过AJAX。

基本上我有一个"等待"页面。它将显示一个图像和一些文字,上面写着"等待对手"。在后台,它需要调用我的checkForOpponent()函数,该函数返回true或false。

如果checkfor对手== true,这个人将被重定向到另一个页面。如果它为false,它将继续每0.5秒调用该方法。

你可以使用javascript和jQuery每半秒检查一次数据库,JS将在(或包含在)你的加载页面:

var MyVar = ''; //whatever the default state is    
window.setInterval(function(){
      $.ajax({
        url:"checkForOpponent.php",
        dataType: 'text',
        data: {state:MyVar}, 
        success:function(data){
          console.log('data loaded: ' + data); //just to check the console
          if(data === "something i want"){
            //Opponent state is good, change whatever you want
          }else{
            //Do the opposite
      });
    }, 500);

在你的checkforobject .php中你可以检查$_POST

if(isset($_POST['state'])){
  //query database
  //depending on returned result
  echo 'something'; //this something will be read in your JS code above and act accordingly
}