[英]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.