Ajax的长轮询与MySQL [英] ajax long polling with mysql

查看:90
本文介绍了Ajax的长轮询与MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用类似于此处所述的脚本:来自mysql的长轮询信息不起作用 在我的网站上,它的工作正常,但是,当我刷新页面或单击其他链接时,我收到错误警报+网站开始严重滞后,有人可以告诉我是什么原因造成的吗?

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?

我的代码:

$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();
});
';

服务器:

<?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);
?>

推荐答案

在$ _GET ['oldid']中的问题,当您单击另一个链接或刷新没有该链接的页面时,变量$ oldID将为空,并且sql将失败. 并且js函数每次调用错误时都保持不变,并且ajax将继续调用keep failing,这将导致无限循环,这会挂起您的网站,我想如果您在firebug上进行检查,您会发现这种情况正在发生.

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

这篇关于Ajax的长轮询与MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆