【发布时间】:2017-02-14 16:05:48
【问题描述】:
假设我有 2 个文件,index.php 和 get_data.php。在 get_data 中,我有一个 sql while 循环从我的数据库输出数据说用户名、图像和自上传以来图像的以秒/计时器为单位的年龄。在索引中,我想调用 get_feed 以显示 while 循环的输出。我只想刷新名为#timer 的计时器 div 而不是其余的数据。我怎样才能做到这一点?现在我只能刷新我在 index.php 中输出到 #response 的所有内容,其中包含图像,因此它会刷新图像,这些图像可能会导致性能下降。
index.php -
<div id="response"></div>
repeatAjax();
function repeatAjax(){
$.ajax({
type: "GET",
url: "get_feed.php",
dataType: "html",
success: function(response){
$("#response").html(response);
},
complete: function() {
setTimeout(repeatAjax,1000);
}
});
};
get_feed.php -
$today_date = date('Y-m-d H:i:s');
$sql = "SELECT image, user, date FROM images";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$image = $row['image'];
$user = $row['user'];
$date = $row['date'];
$timeFirst = strtotime($today_date);
$timeSecond = strtotime($date);
$timeSecond = $timeSecond + 86400;
$timer = $timeSecond - $timeFirst;
echo '<div id="timer">'.$timer.'</div>';
echo '<div id="user">'.$user.'</div>';
echo '<img src="'.$image.'" id="image"';
}
} else {
echo "0 results";
}
上面的脚本可能有错误,我只是为这个例子编写的,但我要做的只是每秒刷新一次计时器,而不刷新图像或用户名。我也担心如果服务器无法处理每秒刷新的负载,如果网站上有很多人的话,我的网站就会崩溃..
谢谢!
【问题讨论】:
-
如果您的需求限制允许,您可以使用 JavaScript 来显示计时器,即使不访问服务器。
-
我该怎么做?看起来我想做的事情很简单,也许我解释错了,这里有一个例子 - Facebook 喜欢按钮,当它点击按钮变成蓝色并且你的喜欢被添加到总数中并实时更新但它没有刷新帖子..我知道我没有点击任何东西,但似乎是同一个想法,@Rohith
标签: php jquery ajax while-loop refresh