dongzhangnong2063 2012-09-11 12:14
浏览 64
已采纳

用mysql进行ajax长轮询

Im using a similar script as described here: long-polling info from mysql not working on my website, its work but, when i either refresh the page or click a different link i get an error alert+the website starts lagging seriously, can some one tell me what is causing this?

my code:

$oldIDq = mysql_query("SELECT * FROM messages ORDER BY id DESC LIMIT 1");
while($oldrow = mysql_fetch_array($oldIDq)){
$oldID = $oldrow['id'];    
}

$func = '
var oldID = '.$oldID.';

function wait() {
$.ajax({
    type: "GET",
    url: "../scripts/msg_scripts/msg.php?oldid=" + oldID,
    async: true,
    cache: false,

    success: function (data){
     var json = eval(\'(\' + data + \')\');  

     if (json[\'msg_content\'] != "") {
      alert("new meassage added");   
     } 

     oldID = json[\'oldID\'];
     setTimeout(\'wait()\',1000);
    },

    error: function(XMLHttpRequest, textStatus, errorThrown){
      alert("error: " + textStatus + "(" + errorThrown + ")");  
      setTimeout(\'wait()\',15000);
    }

});
}

$(document).ready(function(){

    wait();
});
';

server:

<?php 
    session_start();
    $connect = mysql_connect ("localhost", "root", "")

or die ("couldnt connect");
mysql_select_db ("***") or die ("not found"); //if db was   not found die
mysql_query("SET NAMES 'utf8'");

$oldID = $_GET['oldid']; 
$result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
    $last_msg_id = $row['id']; 
}
while($last_msg_id <= $oldID)
{
    usleep(1000);
    clearstatcache();
    $result = mysql_query("SELECT id FROM messages ORDER BY id DESC LIMIT 1");
    while($row = mysql_fetch_array($result))
    {
        $last_msg_id = $row['id'];
    }
}
$response = array();
$response['msg'] = 'new';
$response['oldID'] = $last_msg_id;
echo json_encode($response);
?>
  • 写回答

1条回答 默认 最新

  • duandoucou7200 2012-09-11 12:20
    关注

    proplem in here in $_GET['oldid'] when you click on another link or refresh the page without it the variable $oldID will be empty and the sql will fail. and the js function keep calling itself with nothing changed every time an error accured and the ajax will keep calling keep failing wich will result to an infinite loop that will hang your site and i guess if you check it on firebug you will see that happening.

    dont now if that what you mean hope it help

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”