如何使用php和ajax设置此倒计时?

时间:2013-06-12 18:34:11

标签: php javascript jquery

我有一个永久倒数计时器,我需要设置,我正在努力如何正确地做到这一点。

我正在使用一个名为coutdown的插件,可在此处找到:

http://www.littlewebthings.com/projects/countdown/

所以到目前为止我的设置涉及以下代码:

$(document).ready(function() {
    $('#countdown_contain').countDown({
        targetDate: {
            'day':      23,
            'month':    6,
            'year':     2013,
            'hour':     12,
            'min':      0,
            'sec':      0
        },
        omitWeeks: true
    });
});

所以它正在做的是倒计时到2013年6月23日星期日。当它变为零时,我需要它重置,然后在两周内开始倒数到同一时间。所以基本上我需要一个为期两周的星期日中午倒数计时器。

我的想法是,每次页面加载时都可以对php脚本进行ajax调用,以查看我们在下一个倒计时日期的位置,然后将响应填充到JS变量中,这些变量将成为插件使用的信息。也许这太过分了?

我如何构建我的php或javascript以实现我的目标?

2 个答案:

答案 0 :(得分:3)

我会创建一个计算下一个有效日期的javascript函数,而不是ajax,并使用它来计算计数器时间。这样,就没有额外的服务器交互。

就自动重置而言,使用onComplete事件重新设置控件。


动态构建targetDate结构,我会使用moment.js做这样的事情。请注意,这是我在工作中的“非吸烟者的烟雾”期间编写的理论,所以这是未经测试的。请编辑,如果它不能100%工作,请不要downvote。

function getTargetDate() {
     // initialize the static stuff...
     var retval = { 'hour':12,'min':0,'sec':0 }
     // good news! using Moment.js in the USA, Sunday is considered first day of week
     // so all we have to do is calculate the correct week number...
     var currentWeekOfYear = moment().week(); 
     // assume that we're targeting odd weeks, so 
     //  if it's odd, add 2, if it's even, add 1
     var nextTargetWeek = currentWeekOfYear;
     if( currentWeekOfYear % 2 == 0) {
         nextTargetWeek += 1;
     } else {
         nextTargetWeek += 2;
     }

     var nextTarget = moment().week(nextTargetWeek);

     // moment retains the current day, so we need to set it to sunday.
     nextTarget = nextTarget.day(0);

     // now, enrich the return value
     retval.day = nextTarget.date();
     retval.month = nextTarget.month();
     retval.year = nextTarget.year();

     return retval;
}

答案 1 :(得分:1)

这不是一个确切的答案,但它应该让你走上正确的轨道。

您可以直接将变量回显到您的javascript文件中。

$(document).ready(function() {
$('#countdown_contain').countDown({
    targetDate: {
        'day':      <?php echo(json_encode($day)); ?>,
        'month':    <?php echo(json_encode($month)); ?>,
        'year':     <?php echo(json_encode($year)); ?>,
        'hour':     <?php echo(json_encode($hour)); ?>,
        'min':      <?php echo(json_encode($min)); ?>,
        'sec':      <?php echo(json_encode($sec)); ?>
    },
    omitWeeks: true
});
});

在您的php脚本中,您可以使用strtotime()来计算下一个目标日期。