从MySQL工作不长轮询信息 [英] long-polling info from mysql not working
本文介绍了从MySQL工作不长轮询信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图让长轮询的聊天与阿贾克斯,jQuery的,PHP和MySQL,但事情似乎是错误的(也是我新的长轮询)。
I'm trying to make long-polling based chat with ajax, jquery, php and mysql, but something seems wrong (also i'm new to long-polling).
的index.php:
index.php:
<?php
include 'db.php';
$result = mysql_query("SELECT id FROM chatpoll ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$old_msg_id = $row['id'];
}
?>
<html>
<head>
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
var old_msg_id = <?php echo $old_msg_id; ?>;
function waitForMsg(){
$.ajax({
type: "GET",
url: "poll.php?old_msg_id=" + old_msg_id,
async: true,
cache: false,
success: function(data){
var json = eval('(' + data + ')');
if(json['msg'] != "") {
alert("New msg added to base!");
}
old_msg_id = json['old_msg_id'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
});
}
$(document).ready(function(){
waitForMsg();
});
function load(old_msg_id) //part of code which i'm not using yet
{
$.get('getmsg.php?last_msg_id='+ old_msg_id, function(data){
$('#chat').append(data);
}, 'html');
}
</script>
</head>
<body>
<div id="chat">
</div>
</body>
</html>
和poll.php
<?php
include 'db.php';
$old_msg_id = $_GET['old_msg_id'];
$result = mysql_query("SELECT id FROM chatpoll ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
while($old_msg_id >= $last_msg_id) {
usleep(1000);
clearstatcache();
$old_msg_id = $last_msg_id;
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $old_msg_id;
echo json_encode($response);
?>
它没有显示无论是在index.php文件和poll.php任何错误,但是当我插入的数据有更大的ID比old_msg_id什么也不会发生。
it's not showing any error both in index.php and poll.php, but when i insert data with bigger id than old_msg_id nothing happens..
推荐答案
更改code在poll.php文件如下:
Change code in your poll.php file to following:
<?php
include 'db.php';
$old_msg_id = $_GET['old_msg_id'];
$result = mysql_query("SELECT id FROM chatpoll ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
while($last_msg_id <= $old_msg_id)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT id FROM chatpoll ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $last_msg_id;
echo json_encode($response);
?>
这篇关于从MySQL工作不长轮询信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文