我认为这很简单,但无法弄清楚我的生活..我想刷新一个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从外部文件中调用它来加载所有内容也据我所知..还是新的。 *这不是这个例子的切碎代码而不是全部。
答案 0 :(得分:1)
根据我的评论,你可以这样做:
<强> 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();
<强>定时器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();
})
答案 1 :(得分:0)
将现有的PHP代码放入单独的.php
文件
然后使用名为jquery
的{{1}}方法将该php文件加载到div中。
load()
现在,在上面的代码中是不需要的东西,但可能会有所帮助,那就是$(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
数学内容,以确保没有缓存。