使用jquery刷新php并重新加载图像

时间:2015-06-24 08:49:01

标签: javascript php jquery

我有这个php页面/var/www/oggi1ora.php

首先,我需要执行页面/usr/local/bin/oggi1ora.php来生成图表。

php脚本每5秒正确执行一次,但页面中的图像不刷新... 我怎么解决这个问题?

我需要每5秒/usr/local/bin/oggi1ora.php执行一次。该脚本生成存储在/var/www/grafici/oggi1ora.png

中的图像
<div class="result">
    <?php exec('php -q /usr/local/bin/oggi1ora.php'); ?>
</div>

<div class="oggi1ora">
<html>
    <body>
       <img src="grafici/oggi1ora.png" id="oggi1ora" border="0" />
    </body>
</html>
</div>

<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
    function refresh_div() {
        jQuery.ajax({
            url:'oggi1ora.php',
            type:'POST',
            success:function(results) {
                jQuery(".result").html(results);
            }
        });
    }
    t = setInterval(refresh_div,5000);
</script>

这是新的/var/www/oggi1ora.php

<div class="result">
<?php
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    include('/usr/local/bin/oggi1ora.php');
?>
</div>

<div class="oggi1ora">
<html>
    <img src="grafici/oggi1ora.png" id="oggi1ora" border="0" />
</html>
</div>

<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
    function refresh_div() {
        var d = new Date().getTime();
        jQuery.ajax({
        url:'oggi1ora.php?ts=' + d,
        type:'POST',
            success:function(results) {
            $("#oggi1ora").attr("src", "grafici/oggi1ora.png?ts=" + d);
            }
        });
    }
    t = setInterval(refresh_div,5000);
</script>

1 个答案:

答案 0 :(得分:3)

您可能遇到浏览器缓存问题。一种解决方案是在URL中附加时间戳以确保获取最新版本。或者将服务器端标头设置为不缓存。对于以前的解决方案,您可以尝试:

function refresh_div() {
    var d = new Date().getTime();
    jQuery.ajax({
        url:'oggi1ora.php?ts=' + d,
        type:'POST',
        // rest of your code

对于后者,您可以设置如下标题:

<?php
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

接下来,jQuery(".result").html(results)可能没有做任何事情,因为没有带有类的元素&#34;结果&#34;在你的标记中。

相反,忽略结果并强制图像刷新,如下所示:

function refresh_div() {
    var d = new Date().getTime();
    jQuery.ajax({
        url:'oggi1ora.php?ts=' + d,
        type:'POST',
        success:function(results) {
            $("#oggi1ora").attr("src", "grafici/oggi1ora.png?ts=" + d);
        }
    });
}

更新:如果您也想每5秒拨打一次/usr/local/bin/oggi1ora.php,请include '/usr/local/bin/oggi1ora.php'(或者您的目录结构已设置)或添加exec('php -q /usr/local/bin/oggi1ora.php')在面向网络的/var/www/oggi1ora.php脚本中。

相关问题