繁体   English   中英

AJAX检查更新和php刷新页面

[英]AJAX check for update and php to refresh page

我是AJAX的新手。 要温柔。 我想使用ajax来检查过去十分钟内数据库中是否有任何更新。

1)我有两套代码。 请告诉我哪个是更好的选择,为什么(如果您的代码比我的更好,我欢迎您提出建议)。

2)其次,用于检查更新是否在过去十分钟内的php脚本需要更新第一页,如果更新在最后十分钟内,则需要刷新第一页,我该怎么做?

Ajax选项1:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(function ()
{
$('#slideshow').load('check_time.php');
}, 600000); // refresh every 600000 milliseconds

</script>

Ajax选项2

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "check_time.php", false);
xhttp.send();
document.getElementById("slideshow").innerHTML = xhttp.responseText;
}

PHP脚本检查更新

<?PHP

date_default_timezone_set('Africa/Johannesburg');
$currenttime = date('Y-m-d H:i:s');
$timelessten = date_modify($currenttime,"-10 Minutes");
require_once('connect_pdo.php');
$sqlst = $conn->prepare("SELECT `lastupdate` FROM `Ads`");
$sqlst->execute();
while($resultst = $sqlst -> fetch()){
$updatetime = $resultst["lastupdate"];
}
if($updatetime <= $timelessten){
//Refresh code here. 
}
?>

我已经尝试过header('location: phppage.php'); header('location: phppage.php'); exit(); header('location: phppage.php'); exit();

更新PHP文件

<?php
require_once('connect_pdo.php');

$stmt = $conn->prepare("SELECT COUNT(*) AS count
                     FROM ads
                     WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$stmt ->execute();
while($row = $stmt ->fetch())
{
$update = json_encode($row['count'] > 0);
echo "$update ";
}

?>

您可以在SQL查询中检查新广告:

$sqlst = $conn->prepare("SELECT COUNT(*) AS count
                         FROM ads
                         WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$sqlst->execute();
$row = $sqlst->fetch();

我建议您返回JSON响应:

echo json_encode($row['count'] > 0);

然后,您可以在Javascript代码中执行以下操作:

setInterval(function() {
    $.getJSON("check_time.php", function(update) {
        if (update) {
            $("#slideshow").load("phppage.php");
        }
    })
}, 600000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM