问题描述
我想使每个帖子的时间实时更改.
I want to make the time of each post to change in realTime.
这只是带有时间的字体,因为要在这里很重要.
This is only the font with the time,beacuse this is want is the important here.
<font class="timestamp" postdate="unixTimeStamp" postID="6">2 min ago</font>
<font class="timestamp" postdate="unixTimeStamp" postID="5">4 min ago</font>
<font class="timestamp" postdate="unixTimeStamp" postID="4">9 min ago</font>
这是JavaScript
An this is the javascript
setInterval(updateTimestamps,30000);
var realTime=<?php echo time();?>;
function updateTimestamps(){
$(".timestamp").each(function(i){
var timestamp=$(this).attr("postdate"),
postID=$(this).attr("postID"),
math=realTime-timestamp;
if(math<3600){var dataString='postID='+postID+'×tamp='+timestamp;
$.ajax({
type:"POST",
url:"http://site.com/ajax/humanTime.php",
data:dataString,
cache:false,
success:function(html){
$("[postID='"+postID+"']").html(html);
}
});
}
});
}
在humanTime.php中,我计算时间:
In humanTime.php I calculate the time:
$timestamp = $_POST['timestamp'];
$now=time(); $diff= $now - $timestamp; and so on..
但是问题在于它建立了许多连接,因为每个帖子都调用了脚本.并且以为我可以建立1个连接,将数据排序到一个数组中,然后更改时间.但是我从未使用过json,而且我确定我想要的东西是否真的有可能
But the problem is that it makes to many connections,beacuse the script is called for every post. And thought that maybe i can make 1 connection sort the data into a array and then to change the time. But i never worked with json and i'm sure if what i want is really possible
推荐答案
我会做这样的事情:
setInterval(updateTimestamps,30000);
var ids = new Array();
function updateTimestamps(){
$(".timestamp").each(function(i){
var obj = new Object();
obj.id = $(this).attr("postID");
obj.timestamp = $(this).attr("postdate");
ids.push(obj);
}
$.post("http://site.com/ajax/humanTime.php", {"time": ids}, function(data) {
for (i = 0; i < data.length; i++) {
$("#" + data[i].id).html(data[i].content);
}
}, "json");
}
在humanTime.php中:
And in humanTime.php:
<?php
$ids = json_decode($_POST['time']);
foreach($ids as $id) {
// Calculate human time ...
}
?>
然后返回如下内容:
[{id:1, content:1 minute ago}, {id:3, content: 5 hours ago}]
PS:这是您所要求的解决方案,但我认为Bram的方法更好.
PS: This solution is what you requested, but I think Bram aproach is better.
这篇关于如何从jQuery ajax成功函数返回数组并在循环中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!