【问题标题】:PHP: Longpolling - $current_row & $latest_rowPHP: 长轮询 - $current_row & $latest_row
【发布时间】:2013-05-11 16:17:29
【问题描述】:

在我的 JavaScript 长轮询脚本中,我调用 msgsrv.php 来回显屏幕上尚未显示的 num_rows。这是正在运行的 JavaScript:

<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
    /* Simple helper to add a div.
    type is the name of a CSS class (old/new/error).
    msg is the contents of the div */
    $("#notiWrap.notiZero").html(
        "<div id='notiZero "+ type +"'>"+ msg +"</div>"
    );
}

function waitForMsg(){
    /* This requests the url "msgsrv.php"
    When it complete (or errors)*/
    $.ajax({
        type: "GET",
        url: "http://mediahood.net/widgets/txtr/inc/msgsrv.php",

        async: true, /* If set to non-async, browser shows page as "Loading.."*/
        cache: false,
        timeout:50000, /* Timeout in ms */

        success: function(data){ /* called when request to barge.php completes */
            addmsg("notiMsg", data); /* Add response to a .msg div (with the "new" class)*/
            setTimeout(
                waitForMsg, /* Request next message */
                1000 /* ..after 1 seconds */

            );
        },
    });
};
$(document).ready(function(){
    waitForMsg(); /* Start the inital request */

});
</script>

但是,msgsrv.php 知道数据库中实际的最新行,但它现在不知道页面上加载的最新行的 id。 $num_rows 有效; $loaded_rows 失败。 $loaded_rows 失败,因为当 JS 调用 msgsrv.php 时,它会重置为数据库的实际 num_rows。我需要 PHP 来读取页面上而不是数据库中的 $loaded_rows 是什么,因为我已经知道如何查询最新的行。

这是我的 msgsrv.php:

<?php
/* Send a string after a random number of seconds (2-10) */
sleep(2);

include('/home/alimix/public_html/include/conn.php');

/* Variables */
$nr = mysql_query("SELECT * FROM txtr");
while(mysql_fetch_array($nr))
{$nowrecent =  mysql_num_rows($nr);}

$mr = mysql_query("SELECT * FROM txtr ");
for( $i=0; $i < 1; $i++ )
{$mostrecent = "$nowrecent";}
/* $mostrecent shouldn't equal $nowrecent if new rows aren't loaded*/
    $minus = $nowrecent - $mostrecent;

        if ($minus > 0) {
            //echo $nowrecent;
            echo $minus;
            //echo $mostrecent;
        }
        elseif($minus < 1) {
            echo "nr".$nowrecent."";
            echo " ";
            echo "mr".$mostrecent."";
        }


?>

【问题讨论】:

    标签: php mysql ajax variables long-polling


    【解决方案1】:

    而不是喂这个:

        url: "http://mediahood.net/widgets/txtr/inc/msgsrv.php",
    

    喂这个:

        url: "http://mediahood.net/widgets/txtr/inc/msgsrv.php",
        data: {
          lastID: mylastID
        },
    

    每次获得一行时,将 mylastID 设置为您的最新 ID(并确保 mylastID 在 AJAX 调用的范围内)。就是这样,然后您可以使用 $_GET['lastID'] 恢复该值!

    【讨论】:

    • iono 我需要多长时间才能弄清楚这一点,即使你可能会给我正确的答案。无论如何谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 2011-09-19
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2013-08-08
    • 2012-02-08
    相关资源
    最近更新 更多