您需要将推文检索与用户点击分离。将 AJAX 移动到 JQuery ajax() 调用集以间隔运行。添加一个隐藏元素来保存最新的推文,并使用 AJAX 调用的结果对其进行更新。还要更改 fancybox 调用以使用隐藏元素的内容,而不是让 fancybox 进行 AJAX 调用。
主要HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="scripts/jquery.fancybox.js"></script>
<link rel="stylesheet" type="text/css" href="scripts/jquery.fancybox.css?v=2.1.4" media="screen" />
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$('.fancybox').fancybox();
/*
* call ajax function and update latest
*/
var refreshTweets = function() {
console.log("updating..");
$.ajax({url:"updatetweets.php",success:function(result){
tweets = eval(result);
for(i=0;i<tweets.length;i++){
$("#latesttweet"+(i+1)).html(tweets[i]);
}
}});
}
//set the time in milliseconds here for each refresh
setInterval(refreshTweets , 30000); //Interval
});
</script>
<?php
//Setting up objects, you won't need this part
$tweeters = array("one", "two", "three");
$tmhOAuth = 0;
$r =0;
Class Tweeter{
function __construct(){
return array("bob", "sue", "derek");
}
function getImage(){
return "images/turpin.gif";
}
}
//end set up objects
// Create all Tweeter objects
foreach ($tweeters as $i => $tweeter){
$tweeters[$i] = new Tweeter($tweeter, $tmhOAuth);
}
// Display all Tweeters
foreach ($tweeters as $tweeter){
$r+=1;
echo '<a class="fancybox" href="#latesttweet' . $r . '">';
echo '<img class="tweetTime' . $r . '" id="' . $r . '" src="' . $tweeter->getImage() . '" width="240px" height="240px" /></a>';
echo '<span id="latesttweet'. $r .'" style="display: none;">Tweet text will go here</span>';
}
?>
</body>
</html>
更新推文代码(Ajax php):
<?php
//Setting up objects, ignore this part
$tweeters = array("bob", "sue", "derek");
$tmhOAuth = 0;
$r =0;
Class Tweeter{
private $thetweeter;
function __construct($tweeter){
$this->theTweeter = $tweeter;
}
function getTweet(){
return $this->theTweeter . "'s tweet at ". date('H:i:s') ;
}
}
//end set up
foreach ($tweeters as $i => $tweeter){
$theTweeter = new Tweeter($tweeter, $tmhOAuth);
$tweeters[$i] = $theTweeter->getTweet();
}
header("Content-type: application/json");
echo json_encode($tweeters);
?>