我只收到第一次消息,然后代码停止工作。
我正在学习长轮询(我知道,也会有很多错误和愚蠢)。请帮助。
Jquery 函数在这里。
var timestamp = null;
var last_msg_id = 1;
function chat(id, name) {
$('#chatcom').show('fast');
$.ajax({
type:"Post",
url:"load.php",
data:{
timestamp:timestamp
},
dataType:"json",
async:true,
cache:false,
success:function(data) {
var json = data;
$("#chatcom").html(json['msg']);
last_msg_id = json['last_msg_id_db'];
timestamp = json["timestamp"];
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
}
});
}
load.php 在这里
$filename='data.php';
$lastmodif=isset($_POST['timestamp'])?$_POST['timestamp']:0;
$currentmodif=filemtime($filename);
$last_msg_id=$_POST['last_msg_id'];
$session=new $session;
$sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");
$sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid FROM chat_com");
$row_m=mysqli_fetch_array($sql_m);
$last_msg_id_db=$row_m['maxid'];
$final_response=array();
if($last_msg_id_db>$last_msg_id){
while($row=mysqli_fetch_array($sql)){
$text=$row['mesg'];
$fro=$row['fro'];
$tocomr=$row['tocom'];
$handle = fopen('data.php', 'a');
fwrite($handle, $text);
fclose($handle);
}
}
while($currentmodif<=$lastmodif){
usleep(10000);
clearstatcache();
$currentmodif=filemtime($filename);
}
$response=array();
$response['msg']=file_get_contents($filename);
$response['last_msg_id_db']=$last_msg_id_db;
$response['timestamp']=$currentmodif;
echo json_encode($response);