2012-03-20 2 views
0

각 게시물의 시간을 실시간으로 변경하고 싶습니다.jQuery ajax success 함수에서 배열을 반환하고 루프에서 사용하는 방법은 무엇입니까?

이것은 시간이있는 글꼴 일 뿐이며, 여기에 중요한 것은 beacuse입니다.

<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> 

이 나는 ​​시간을 계산 humanTime.php에서 자바 스크립트

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+'&timestamp='+timestamp; 

      $.ajax({ 
        type:"POST", 
        url:"http://site.com/ajax/humanTime.php", 
        data:dataString, 
        cache:false, 
        success:function(html){ 
           $("[postID='"+postID+"']").html(html); 
        } 

      }); 

    } 

}); 

} 

입니다 :

$timestamp = $_POST['timestamp']; 

$now=time(); $diff= $now - $timestamp; and so on.. 

그러나 문제는 스크립트가 beacuse는 많은 연결을 만드는 것입니다 모든 게시물을 요구했다. 그리고 아마 하나의 연결을 배열로 정렬 한 다음 시간을 변경할 수 있다고 생각했습니다. 하지만 난 JSON과 함께 일한 적이 무엇을 내가 원하는 것은 내가 같은 것을 할 것

+1

당신은 글꼴 태그는 HTML4에서 사용되지 오른쪽 HTML5에서 제거되는 것을 알 수 있습니까? –

+0

와우, 90 년대는 사라지고 그걸로 ''- 태그! – Christoph

+0

그래도 글꼴 태그 대신 무엇을 사용할 수 있습니까? – Ben

답변

1

정말 가능하다면 나는 확신 :

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 :

<?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}] 
,536,

추신 :이 해결책은 당신이 요청한 것이지만, 나는 Bram aproach가 더 좋다고 생각합니다.

+0

humanTime.php에서 데이터에 액세스하는 방법 json과 함께 일한 적이없는 사람 – Ben

+0

내 게시물을 다시보십시오. – MatuDuke

2

왜 인간 시간 서버를 계산합니까? 당신은 클라이언트 측 완벽하게 계산할 수 있습니다.

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>를 사용합니다. 당신의 간격에 클라이언트 측의 처리에 대해 어떻게

+0

필자의 예제에서, 나는 여전히 PHP echo()를 time()으로 사용한다. 이것은 약간 부정확 할 것이다. javascript date 객체로 작업하도록 코드를 변경하는 것이 좋습니다. – Bram

+0

그러나 클라이언트 컴퓨터에 시간이 올바르게 설정되지 않은 경우에는 어떻게해야합니까? – MatuDuke

+0

네,하지만이 근무하지만 여전히 변경할 수있는 currentTime을 원하기 때문에 나는 서버 측 스크립트를 사용해야합니다. 나는 단지 인간의 시간으로 바꾸고 싶지만 ex : facebook에 대해 매 20 초마다 업데이트하고 싶다. 각 포스트 생성 시간은 업데이트 중이다. – Ben

0
<!-- if you like something simple :) --> 
<span class="timestamp" data-unix="<?php echo time();?>">posted now</span> 
<script type="text/javascript"> 
setInterval(function() { 
    $('span').each(function() { 
     var d = new Date(); 
     // difference in minutes from now 
     var diff = Math.round(d.getTime()/60000 - $(this).attr('data-unix')/60); 
     $(this).html(diff + ' mins ago'); 
    }); 
}, 60000); 
</script> 
0

:

샘플 마크 업 div에 수 등 스팬

<div class="timestamp" postID="6"></div> 
<div class="timestamp" postID="2"></div> 
<div class="timestamp" postID="3"></div> 

이 현재와 미래 및 일반 지원합니다.

var time_formats = [ 
    [60, 'just now', 1], 
    [120, '1 minute ago', '1 minute from now'], 
    [3600, 'minutes', 60], 
    [7200, '1 hour ago', '1 hour from now'], 
    [86400, 'hours', 3600], 
    [172800, 'yesterday', 'tomorrow'], 
    [604800, 'days', 86400], 
    [1209600, 'last week', 'next week'], 
    [2419200, 'weeks', 604800], 
    [4838400, 'last month', 'next month'], 
    [29030400, 'months', 2419200], 
    [58060800, 'last year', 'next year'], 
    [2903040000, 'years', 29030400], 
    [5806080000, 'last century', 'next century'], 
    [58060800000, 'centuries', 2903040000] 
    ]; 

function prettydate(date_str) { 
    var time = ('' + date_str).replace(/-/g, "/").replace(/[TZ]/g, " "); 
    var seconds = (new Date() - new Date(time))/1000; 
    var token = 'ago'; 
    var list_choice = 1; 
    if (seconds < 0) { 
     seconds = Math.abs(seconds); 
     token = 'from now'; 
     list_choice = 2; 
    } 
    var i = 0, 
     format; 
    while (format = time_formats[i++]) if (seconds < format[0]) { 
     if (typeof format[2] == 'string') return format[list_choice]; 
     else return Math.floor(seconds/format[2]) + ' ' + format[1] + ' ' + token; 
    } 
    return time; 
} 

// these would normally come from your ajax/creation of the element 
$('.timestamp[postID=6]').data('postdate', '2012-03-20T09:24:17Z'); 
$('.timestamp[postID=2]').data('postdate', '2012-03-20T10:24:17Z'); 
$('.timestamp[postID=3]').data('postdate', '2012-03-20T08:24:17Z'); 

function formatTimes() { 
    $('.timestamp').each(function() { 
     $(this).text(prettydate($(this).data('postdate'))); 
    }); 
} 
setTimeout(formatTimes, 30000); 

근무 예 : http://jsfiddle.net/MarkSchultheiss/6HKmS/

관련 문제