2015-05-29 51 views
0

爲了避免我的服務器上多要求,我想實現一個池。所以我做了要求,一旦給我的數據,如果它發現它每隔30秒,或者30秒過去了!

//getchat.php 

$pool=0; 
$chatmsg= array(); 

while($pool<30 && count($chatmsg)==0){ 

    $result = mysqli_query($con,"SELECT * FROM chat WHERE id > ".addslashes($_GET['id'])." ORDER BY id ASC"); 
    $i=0; 
    while($row = mysqli_fetch_assoc($result)) { 
     $chatmsg[$i]=array("message"=>htmlspecialchars_decode(htmlentities($row["message"]))); 
     $i++; 
    } 

    sleep(1); 
    $pool++; 
} 

echo json_encode($chatmsg); 
flush(); 
//script.js 

setInterval(function() { 
    $.get("getchat.php", { 
     id: chatid 
    }, function(data) { 
     console.log(data); 
    }); 

}, 30000); 

但消息顯示後30個secondes我在做什麼錯

編輯:我終於發現:

秒後0

function getchat(){ 
 
$.get("getchat.php", { 
 
     id: chatid 
 
    }, function(data) { 
 
     console.log(data); 
 
     getchat(); 
 
    }); 
 

 
}

+0

如果您從瀏覽器中調用「getchat.php?id = someid」,會發生什麼?它實際上是否返回任何json? –

+0

是的!我擁有所有的json – lopata

+2

也許你應該考慮web套接字,而不是像你的服務器端代碼那樣使用'sleep()'。 –

回答

0

該信息表示,因爲你必須的間隔。它只在30秒後被調用。如果你想立即調用它,你可以更改代碼,如下所示:

//script.js 

function getChat() { 
    $.get("getchat.php", { 
     id: chatid 
    }, function(data) { 
     console.log(data); 
    }); 
} 
getChat(); 
setInterval(getChat, 30000); 

編輯

我做了我自己的測試,以重現這種情況:

// index.php 
while (!file_exists(__DIR__ . '/flag')) { 
    sleep(1); 
} 

echo date('r'); 
flush(); 
die; 


// index.html 

<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> 
<script type="text/javascript"> 

function getChat() { 
    $.get(
     "index.php", 
     {}, 
     function(data) { 
      console.log(data); 
     } 
    ); 
} 
getChat(); 
setInterval(getChat, 10000); 
</script> 
</head> 
<body> 
</body> 
</html> 

每當我打電話給index.html,我可以在控制檯中看到一個待處理的請求。在我創建文件「標誌」後,它立即停止,並在console.log中獲得一個日期。

我會建議你兩兩件事:

  1. 複查控制檯待處理的請求。他們應該在那裏跑步。

  2. 重新創建你的PHP代碼更簡單的情況,而不涉及DB。

+0

是的,我已經有這個,但是當我發送一條新消息後,它不會立即顯示 – lopata

+0

那麼爲什麼它會立即顯示?你只需要每30秒鐘更新一次。如果你睡在PHP端,你也可以將setInterval時間改爲1秒。但是這會在某個點 –

+0

中破壞你的服務器,因爲它應該顯示最後一個待處理的setInterval請求的請求 – lopata