2016-11-16 89 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,請選擇我的答案:) –