2016-11-16 94 views
0

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

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

如果checkForOpponent == true,该人将被重定向到另一个页面。如果它是错误的,它将每隔0.5秒继续调用该方法。

+0

AJAX或WebSockets是你解决这个问题的方法。 – Turrican

+0

查找CRON作业。 –

+0

你应该使用“cron”,这里是一个链接http://stackoverflow.com/questions/18737407/how-to-create-cron-job-using-php –

回答

0

您可以张贴到检查数据库的第二个使用JavaScript半你每次和jQuery PHP页面, 的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); 

在你checkForOpponent.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 
} 
+0

谢谢!它现在工作完美。 – Engima

+0

@Engima yw,请选择我的答案:) –