簡體   English   中英

如何從jQuery ajax成功函數返回數組並在循環中使用它?

[英]How to return an array from jQuery ajax success function and use it in a loop?

我想使每個帖子的時間實時更改。

這只是帶有時間的字體,因為這要重要在這里。

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

我會做這樣的事情:

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

PS:您可以根據需要提供此解決方案,但我認為Bram的方法更好。

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

在您的間隔內如何處理客戶端:

樣本標記可以是div,span等。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM