【问题标题】:how to refresh div without refreshing all php data如何在不刷新所有php数据的情况下刷新div
【发布时间】:2017-02-17 02:06:02
【问题描述】:

我认为这很简单,但我一生都无法弄清楚。我想在不刷新所有内容的情况下刷新 div。我在每个图像上都有一个计时器,从 24 小时倒计时到 0 然后消失。 . 一切正常,但我似乎不能只刷新计时器 div..

我的 php -

$date = date('Y-m-d H:i:s');

$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
    $path = $row['path'];
    $user = $row['user'];
    $update = $row['update_date'];

    $timeFirst  = strtotime($date);
    $timeSecond = strtotime($update);
    $timeSecond = $timeSecond + 86400;
    $timer = $timeSecond - $timeFirst;

if($timer <= 0){

}else{
    echo '<img id="pic" src="/v2/uploads/'.$path.'"/>';
    echo '<div id="user">#'.$user.'</div>';
    echo '<div id="timer">'.$timer.' </div>';

    }
  }
}

我想仅以 1 秒的间隔刷新计时器,而不是图像。我知道我可以使用 ajax 从加载所有内容的外部文件中调用它。据我所知,这仍然是新的. *side not this is cpped code for the example not all.

【问题讨论】:

  • Ajax 不刷新任何内容。您可以使用 ajax 从服务器请求数据,并随心所欲地处理该数据。您需要制作一个只返回 $timer 数据的 php 脚本,然后您可以使用 jQuery 轻松替换旧数据。
  • 是的,你是对的,我的意思是用 ajax 加载它,好吧,听起来我可能需要以某种方式附加它?我不擅长那个你可能有一个例子吗?谢谢@NikolaR。

标签: javascript php jquery ajax refresh


【解决方案1】:

根据我的评论,您可以这样做:

  1. 将类“timer”添加到您的#timer 元素(如果您有多个#timer 元素,请为每个元素使用不同的ID)。
  2. 创建 php 脚本,该脚本在调用时返回新的 $timer:

ajax-timer.php

<?php

/* include file where $conn is defined */


$response = array();

$date = date('Y-m-d H:i:s');

$sql = "SELECT * FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $update = $row['update_date'];

        $timeFirst  = strtotime($date);
        $timeSecond = strtotime($update);
        $timeSecond = $timeSecond + 86400;
        $timer = $timeSecond - $timeFirst;


        if($timer > 0) {
            //Add just timer to response array
            $response[] = $timer;
        }
    }
}

//Return json response and handle it later in ajax:
echo json_encode(array(
    'result'=>empty($response) ? 0 : 1,
    'data'=>$response));
die();
  1. 使用 $.ajax 从 ajax-timer.php 请求数据并在收到响应时填充数据:

timer-update.js

var ajaxTimerThread = 0;
var ajaxTimerRunning = false;

function ajaxTimerRun() {
    //Prevent running function more than once at a time.
    if(ajaxTimerRunning)
        return;

    ajaxTimerRunning = true;
    $.post('ajax-timer.php', {}, function (response) {
        ajaxTimerRunning = false;
        try {
            //Try to parse JSON response
            response = $.parseJSON(response);
            if (response.result == 1) {
                //We got timer data in response.data.
                for(var i = 0; i < response.data.length; i++) {
                    var $timer = $('.timer').eq(i);
                    if($timer.length) {
                        $timer.html(response.data[i]);
                    }
                }
            }
            else {
                //Request was successful, but there's no timer data found.
                //do nothing
            }
            //Run again
            ajaxTimerThread = setTimeout(ajaxTimerRun, 1000); //every second
        }
        catch (ex) {
            //Could not parse JSON? Something's wrong:
            console.log(ex);
        }
    });
}

$(document).ready(function() {
    // Start update on page load.
    ajaxTimerRun();
})

【讨论】:

  • 好的,所以我进行了更改并在日志中得到了这个 - SyntaxError: Unexpected token
  • 在 catch(ex) { } 中添加 console.log(response) 并查看您得到的响应。
  • 这是输出 - 致命错误:在 /ajax-timer.php 中对非对象调用成员函数 query()
  • 您必须包含定义$conn 的文件。
  • 哇,我疯了..我的所有混乱都没有引用我的 conn 文件..它工作得很好!再次感谢@NikolaR。你太棒了!
【解决方案2】:

将现有的 php 代码放入单独的 .php 文件中

然后使用名为load()jquery 方法将该php 文件加载到您的div 中。

$(document).ready(function() {
    $("#div_ID_you_want_to_load_into").load("your_php_file.php");
    var pollFrequency = function() {
        if (document.hidden) {
            return;
        }
        $("#div_ID_you_want_to_load_into").load('your_php_file.php?randval='+ Math.random());
    };
    setInterval(pollFrequency,18000); // microseconds, so this would be every 18 seconds
});

现在,在上面的代码中,有些东西是不需要的,但可能会有所帮助,那就是if (document.hidden) {return;},它基本上是对浏览器的一个命令,如果浏览器选项卡不在焦点上,请不要触发setInterval投票。

保留randval= 数学内容也是一个好主意,只是为了确保没有缓存。

【讨论】:

  • 好的,谢谢!我看到这会将外部数据加载到当前页面的 div 中,但它会刷新所有数据吗?我看不到你在哪里刷新计时器。
  • $.load 倾向于冻结浏览器,直到加载数据。异步 ajax 请求是更好的选择。
猜你喜欢
  • 2017-05-11
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 2015-11-13
相关资源
最近更新 更多