我試圖修改長輪詢代碼以適應我的情況。 我想從MySQL數總數,如果數量變化(增加或減少),它會通知我。長輪詢不會停止
問題是while循環保持循環。我怎樣才能阻止它?每當總和變化時,我只需要通知。
<?php
include("db.php");
$result = mysql_query("SELECT sum(r) as totalsum FROM (SELECT colA, colB, COUNT(*) AS r FROM product GROUP BY productid) AS t");
while($row = mysql_fetch_array($result))
{
$old_totalsum = $row['totalsum'];
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var old_totalsum =<?php echo $old_totalsum; ?>;
function waitForMsg(){
$.ajax({
type: "GET",
url: "poll.php?old_totalsum=" + old_totalsum,
async: true,
cache: false,
success: function(data){
var json = "eval(+(" + data + ")+)";
if(json['msg'] != "") {
alert(data);
}
old_msg_id = json['old_msg_id'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
}); // end ajax
} //end waitformsg
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<div id="chat">
</div>
</body>
</html>
<----------------------------------------------------------->
poll.php
<----------------------------------------------------------->
<?php
include("db.php");
$old_totalsum = $_GET['old_totalsum'];
$result = mysql_query("SELECT sum(r) as totalsum FROM (SELECT colA, colB, COUNT(*) AS r FROM product GROUP BY productid) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
}
while($last_sum < $old_totalsum || $last_sum > $old_totalsum)
while($last_sum <= $old_totalsum)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT sum(r) as totalsum FROM (SELECT colA, colB, COUNT(*) AS r FROM product GROUP BY productid) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
//echo $last_sum;
//return;
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $last_sum;
echo json_encode($response);
?>
<------------------------------------------->
我沒有看到任何鏈接 – Dave
請再次檢查 – user1042911
哪個'while'循環不退出? 'while($ last_sum <= $ old_totalsum)'或'while($ last_sum <$ old_totalsum || $ last_sum> $ old_totalsum)' –