来自mysql不工作的长轮询信息不工作

问题描述:

我想与ajax,jquery,php和mysql进行基于长轮询的聊天,但有些东西似乎不对(我也是新的长轮询)。来自mysql不工作的长轮询信息不工作

的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没有任何反应..

+0

我要把炸弹放在这里。你显然开始学习PHP,所以你不妨养成一个好习惯;现在,'ext/mysql',又名'mysql_'-函数已经[弃用](https://wiki.php.net/rfc/mysql_deprecation)很长一段时间了。您应改用[mysqli](http://php.net/manual/en/mysqli.query.php)或[PDO](http://php.net/manual/en/book.pdo.php) 。 – Dencker 2016-01-25 12:33:01

更改密码在你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($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); 
?> 
+0

它的工作,谢谢! – 2012-07-12 15:04:53