Php 图像闪烁ajax轮询

Php 图像闪烁ajax轮询,php,javascript,ajax,Php,Javascript,Ajax,我目前正在使用ajax轮询定期从数据库中获取新数据并将其显示给用户。它工作得很好,只是有时候,获取的图像开始闪烁,然后闪烁突然停止。以下是获取数据的JavaScript: function loadLog(){ $.ajax({ url: "stream.php", cache: false, success: function(html){ $("#inner").html(html); }

我目前正在使用ajax轮询定期从数据库中获取新数据并将其显示给用户。它工作得很好,只是有时候,获取的图像开始闪烁,然后闪烁突然停止。以下是获取数据的JavaScript:

function loadLog(){     
    $.ajax({
        url: "stream.php",
        cache: false,
        success: function(html){
$("#inner").html(html);         
        }
    });
}
setInterval (loadLog, 2500);

php文件包含检查数据库中新数据的基本sql命令。因此,这些命令每2.5秒调用一次。如果post类型是一个图像,它会伴随一条语句,例如:user_name posted a new image,xseconds ago。语句从不闪烁,但图像却闪烁。有没有办法阻止图像的闪烁?(有趣的是,如果数据库已经有图像,那么只有新发布的图像闪烁,而旧图像没有。因此,如果总共有3个图像,两个旧图像和一个新图像,那么新图像闪烁,而其他图像不闪烁,尽管整个脚本正在轮询,而不是特定的图像。)

我猜这是因为每次都要替换
#internal
div的HTML,因此它会被重新渲染

最优雅的方法是只获取新项目(通过将timestamp参数传递给stream.php,即
stream.php?timestamp=X
,并且只返回提要中自时间戳之后的项目,然后
.prepend();
将内容放入
#inner
div


另一个建议是将该内容加载到一个新的隐藏div中,以使其完全呈现,然后快速显示/隐藏旧div。

尝试只更新#inner的一部分。例如,如果图像未更改,则只更新文本。如果图像已更改,则将其替换为新的。我认为在这种情况下,您不会注意到闪烁效果。还可以查看http这些图像的标题-可能存在不正确的过期、上次修改等。标题和浏览器会多次加载相同的图像。

从最近几天开始,我一直在处理相同的问题,最后我得到了以下示例代码

您需要的是将上次更新的
时间戳
传递给新请求,并根据该
时间戳
查找传递的
时间戳
和当前
时间戳
之间的记录

Index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>testing comet</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="css/style.css" />
        <script type="text/javascript" src="js/jquery.js"></script>
    </head>
    <body>

    <div id="content"></div>

<script type="text/javascript">

    var Comet = function (data_url)
    {
        this.timestamp = 0;
        this.url = data_url;  
        this.noerror = true;

        this.connect = function()
        {
            var self = this;

            $.ajax(
            {
                type : 'post',
                url : this.url,
                dataType : 'json', 
                data :
                {
                    'timestamp' : self.timestamp
                },
                success : function(response)
                {
                    self.timestamp = response.timestamp;
                    self.handleResponse(response);
                    self.noerror = true;          
                },
                complete : function(response)
                {
                    if (!self.noerror)
                    {
                        setTimeout(function(){ comet.connect(); }, 5000);           
                    }
                    else
                    {
                        self.connect(); 
                    }
                    self.noerror = false; 
                }
            });
        }

        this.disconnect = function() {}

        this.handleResponse = function(response)
        {
            $('#content').append('<div>' + response.msg + '</div>');
        }

        this.doRequest = function(request) {
            $.ajax(
            {
                type : 'post',
                url : "index.php",
                data :
                {
                    'msg' : request,
                    'submit' : "Send"
                }
            });
        }
    }

    var comet = new Comet('./backend.php');
    comet.connect();
</script>
</body>
</html>
<?php

    $filename  = dirname(__FILE__).'/data.txt';

    $msg = isset($_GET['msg']) ? $_GET['msg'] : '';
    if ($msg != '')
    {
        file_put_contents($filename,$msg);
        die();
    }

    $lastmodif    = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
    $currentmodif = filemtime($filename);
    while ($currentmodif <= $lastmodif) // check if the data file has been modified
    {
        usleep(10000); // sleep 10ms to unload the CPU
        clearstatcache();
        $currentmodif = filemtime($filename);
    }

    $response = array();
    $response['msg']       = file_get_contents($filename);
    $response['timestamp'] = $currentmodif;
    echo json_encode($response);
    flush();
?>

希望这能对您有所帮助。

太好了!谢谢,这对我来说是成功的,出于好奇,您知道为什么新信息首先会闪烁吗?我想听听您的意见。
<?php
date_default_timezone_set('Asia/Kolkata');
$connection = mysql_connect('localhost','root','')or die(mysql_error());
$database   = mysql_select_db('stackoverflow')or die(mysql_error());

function get_date()
{
    $query = mysql_query("show table status from stackoverflow like 'last_update'")or die(mysql_error());

    $row = array();
    while($result = mysql_fetch_assoc($query))
    {
        $row[] = $result;
    }

    return strtotime($row[0]['Update_time']);
}


$lastmodif    = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
$currentmodif = get_date();

while ($currentmodif <= $lastmodif)
{
    usleep(10000);
    clearstatcache();
    $currentmodif = get_date();
}

$query_db = mysql_query("SELECT UNIX_TIMESTAMP(last_update.created) AS DATE,last_update.* FROM last_update WHERE UNIX_TIMESTAMP(last_update.created) BETWEEN '".$lastmodif."' AND '".$currentmodif."'")or die(mysql_error());

$row_db = array();
$response = array();
while($result_db = mysql_fetch_assoc($query_db))
{
    $response['msg'][]       = $result_db['title'];
}

$response['timestamp'] = $currentmodif;
$response['lastmodif'] = $lastmodif;
echo json_encode($response);
flush();