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

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

报告相同问题?

悬赏问题

  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?
  • ¥15 QTOF MSE数据分析
  • ¥15 平板录音机录音问题解决
  • ¥15 请问维特智能的安卓APP在手机上存储传感器数据后,如何找到它的存储路径?