【问题标题】:ajax long polling with mysql使用 mysql 进行 ajax 长轮询
【发布时间】:2012-09-11 12:14:00
【问题描述】:

我正在使用此处描述的类似脚本:long-polling info from mysql not working 在我的网站上,它的工作,但是,当我刷新页面或单击不同的链接时,我收到错误警报 + 网站开始严重滞后,有人可以告诉我是什么原因造成的吗?

我的代码:

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

【问题讨论】:

  • 啊啊啊!帮助! eval === evil 使用 JSON.parse(jsonString) 代替!你甚至不需要解析!如果您添加dataType: 'json'参数,jquery可以为您完成!

标签: php jquery mysql ajax


【解决方案1】:

$_GET['oldid'] 中的问题当您单击另一个链接或在没有它的情况下刷新页面时,变量 $oldID 将为空并且 sql 将失败。 并且每次发生错误时,js 函数都会不断调用自身而没有任何改变,并且 ajax 将继续调用 keep failed ,这将导致无限循环,这将挂起您的网站,我想如果您在 firebug 上检查它,您会看到这种情况发生。

现在不要,如果你的意思是这样,希望对你有帮助

【讨论】:

  • 如果 null 返回 -1,您可以检查 oldid 是否为 null 并在 js 中检查响应 = -1 是否取消 wait() 调用
  • 所以,在服务器端:$oldID = $_GET['oldid']; if($oldID == ""){$oldID == -1}?并在 js 上?
  • @durian 否 if($oldID == ""){$response=-1} 和 js if(data != '-1'){var json = eval(\'( \' + 数据 + \')\'); if (json[\'msg_content\'] != "") { alert("new meassage added"); } oldID = json[\'oldID\']; setTimeout(\'等待()\',1000); } 试试这个。
  • @durian ok 打开你的 firebug 并检查浏览器发出了多少 ajax 请求及其状态
  • 我不使用firebug,但我现在下载了,你能告诉我应该在哪里寻找请求吗?
猜你喜欢
  • 1970-01-01
  • 2013-10-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2017-05-15
  • 2018-11-16
  • 1970-01-01
相关资源
最近更新 更多