简体   繁体   English

AJAX检查更新和php刷新页面

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

I am new to AJAX. 我是AJAX的新手。 Be gentle. 要温柔。 I want to use ajax to check if there are any update in the database in the past ten minutes. 我想使用ajax来检查过去十分钟内数据库中是否有任何更新。

1) I have two sets of code for that. 1)我有两套代码。 Please tell me which one is the better choice and why (if you have better code than mine, I am open for suggestions). 请告诉我哪个是更好的选择,为什么(如果您的代码比我的更好,我欢迎您提出建议)。

2) Secondly, the php script to check if update was during the past ten minutes, needs to update the first page which needs to be refreshed in case the update was in the last ten minutes, How do I do that? 2)其次,用于检查更新是否在过去十分钟内的php脚本需要更新第一页,如果更新在最后十分钟内,则需要刷新第一页,我该怎么做?

Ajax option 1: 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 Option 2 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 script to check for update 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. 
}
?>

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

Update PHP File 更新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 ";
}

?>

You can check for new ads in the SQL query: 您可以在SQL查询中检查新广告:

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

I suggest that you return a JSON response: 我建议您返回JSON响应:

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

Then in the Javascript code you can do: 然后,您可以在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