尝试在 Javascript 中使用 PHP 变量

Trying to use PHP variable in Javascript

我正在尝试将 php 变量引入我的 javascript 代码中以用于倒数计时器。由于基于时间戳 php 变量发生的其他功能,我也需要在 php 中。

<?php  $access = '1443907640'; ?>
<script>
    $(function() {
        var access = <?php echo $access ?>;
        var note = $('.note'),

        ts = (new Date(access * 1000)).getTime() + 1 * 24 * 60 * 60 * 1000;


        $('.countdown').countdown({
        timestamp: ts,
        callback: function(days, hours, minutes, seconds) {

            var message = "";

            message += days + "<small class='opacity'>D</small>, ";
            message += hours + "<small class='opacity'>H</small>, ";
            message += minutes + "<small class='opacity'>M</small>, ";
            message += seconds + "<small class='opacity'>S</small>";

            note.html(message);

        }


        });
    });
</script>   

然后我在这里用html调用它但是不起作用

<div class="note"></div>

也许可以考虑在 PHP-echo 后加一个分号。

<?php echo $access; ?>

或简短版本:

<?=$access?>

第 4 行:

var access = <?=$access?>;

var access = '<?=$access?>'; //if $access would be typeof string

我认为您代码中的真正问题出在这一行的末尾:

var note = $('.note'),

, 替换为 ;,它应该可以工作。

注意:var access = <?php echo $access ?>;在我的测试中工作正常。


解决以下错误:

TypeError: $(...).countdown is not a function

您应该添加 jquery.countdown 脚本:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.countdown/2.1.0/jquery.countdown.js"></script>

希望对您有所帮助。