0

我在 Django 中使用jQuery Coundown 插件为每个视图生成准确和同步的数据。

对于所有浏览器上显示的同步时间,我使用插件的 serverSync 功能来传递数据(与示例非常相似),如下所示:

function serverTime() { 
    var time;
    $.ajax({url: '/ajax/get-server-time/', 
        async: false, dataType: 'text', 
        success: function(text) { 
            time = new Date(text); 
        }, error: function(http, message, exc) { 
            time = new Date(); 
    }});
    return time;
}

我的倒计时初始化选择器函数就是这样(我通过 Django 将 unixtime 添加到元素的 endDatetime 数据中):

function initAllTimers(selected){
    $(selected).each(function(){
        endDatetime = new Date($(this).attr("data-unixtime") * 1000);
        $(this).countdown({until: endDatetime, serverSync: serverTime});
    });
}

Django 模板生成每个字段以填充计数,如下所示:

<span class="timeLeft" data-unixtime="1334898000"></span>

我将时间计数应用于这些字段,如下所示:

initAllTimers('.timeLeft');

最后是 Django 查看方法或为此插件生成时间戳以检索(通过我的 serverTime() 方法):

#points to /ajax/get-server-time/
def get_server_time(request):
    now = datetime.now()
    response = HttpResponse( now.isoformat())
    response['Expires'] = 'Fri, 1 Jan 2010 00:00:00 GMT'
    response['Content-Type'] = 'text/plain; charset=utf-8'
    response['Cache-Control'] = 'no-cache, must-revalidate'
    return response 

它可以正确渲染,但不会在不同的计算机之间同步,我的 Mac 显示的剩余时间与我的 windows 计算机不同。

我怀疑我在这部分犯了一个错误:

倒计时示例中的 php 示例$now->format("M j, Y H:i:s O")."\n";与我的 python 函数相同datetime.now().isoformat()吗?

4

1 回答 1

0

datetime.now().isoformat()不等同于$now->format("M j, Y H:i:s O")

PHP 的格式转义在这里解释http://php.net/manual/en/function.date.php

您可以使用strftime()Python 正确格式化时间戳;文档可在此处获得 http://docs.python.org/library/datetime.html#strftime-strptime-behavior

.strftime("%b %d, %Y %H:%M:%S %z")应该与 PHPformat()调用几乎相同;如果您没有从 获得合适的偏移量%z,您可以手动将+0000自己添加到 Python 字符串中。

于 2012-04-14T15:04:51.977 回答