我想让每个帖子的时间实时变化。
这只是带有时间的字体,因为这在这里很重要。
<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
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 中我计算时间:
$timestamp = $_POST['timestamp'];
$now=time(); $diff= $now - $timestamp; and so on..
但问题是它会建立许多连接,因为每个帖子都会调用该脚本。并认为也许我可以建立 1 个连接将数据排序到一个数组中,然后更改时间。但我从未使用过 json,我确定我想要的是否真的可能
最佳答案
服务器端为什么要计算人类时间?您也可以在客户端完美地进行这些计算。
setInterval(updateTimestamps,30000);
var currentTime=<?php echo time();?>;
function updateTimestamps(){
$(".timestamp").each(function(i){
var timestamp=$(this).attr("postdate");
$(this).text(humanTime(currentTime, timestamp));
});
}
function humanTime(currentTime, timestamp)
{
var diff = currentTime - timestamp,
minute = 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
if (isNaN(diff) || diff < 0) {
return ""; // return blank string if unknown
}
if (diff < second * 2) {
// within 2 seconds
return 'right now';
}
if (diff < minute) {
return Math.floor(diff / second) + 'seconds ago';
}
if (diff < minute * 2) {
return 'about one minute';
}
if (diff < hour) {
return Math.floor(diff / minute) + 'minutes ago';
}
if (diff < hour * 2) {
return 'about an hour ago';
}
if (diff < day) {
return Math.floor(diff / hour) + 'hours ago';
}
if (diff > day && diff < day * 2) {
return 'yesterday';
}
if (diff < day * 365) {
return Math.floor(diff / day) + 'days ago';
}
else {
return 'more then a year ago';
}
}
该函数借用自:http://www.queness.com/post/8567/create-a-dead-simple-twitter-feed-with-jquery
如上所述:使用 <span>
标签或 HTML5 标签 <time>
.
关于java - 如何从 jQuery ajax 成功函数返回一个数组并在循环中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9787159/