如何将php变量传递给javascript

时间:2017-03-10 12:05:42

标签: javascript php

如何将从数据库调用的php日期变量传递给此脚本?我尝试了下面的代码,但它不起作用:

$(function(){
    $('#js-countDown').yuukCountDown({
        starttime: '<?php echo $dnow; ?>',
        endtime: '<?php echo $dtym; ?>',
        notStartCallBack: function(time){
            console.log("Ready");
        },
        startCallBack: function(time){
            console.log("Running");
        },
        endCallBack: function(time){
            console.log("Complete");
        }
    });
});

<小时/> 它与下面的这个完美配合,上面的回显完全相同的日期时间格式如下:

$(function(){
    $('#js-countDown').yuukCountDown({
        starttime: '2017/03/09 00:00:00',
        endtime: '2017/03/31 10:59:59',
        notStartCallBack: function(time){
            console.log("Ready");
        },
        startCallBack: function(time){
            console.log("Running");
        },
        endCallBack: function(time){
            console.log("Complete");
        }
    });
});

3 个答案:

答案 0 :(得分:1)

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

答案 1 :(得分:0)

试试这个

$(function(){
    $('#js-countDown').yuukCountDown({
        starttime: "<?php echo json_encode($dnow); ?>",
        endtime: "<?php echo json_encode($dtym); ?>",
        notStartCallBack: function(time){
            console.log("Ready");
        },
        startCallBack: function(time){
            console.log("Running");
        },
        endCallBack: function(time){
            console.log("Complete");
        }
    });
});

答案 2 :(得分:0)

试试这个: -

我已经完成了CI,但是在核心php中你可以这样做: - 这是你的控制器: -

<?php
class Test extends CI_Controller {
    function __construct() {
        parent::__construct();
        $this->load->model('test');
    }

    public function index($page = 'profile-page')
    {
        $data['start_time'] = $this->test_model->get_start_time();
        $data['end_time'] = $this->test_model->get_end_time();
        $this->load->view('test_view', $data);

    }
}

在型号上: -

创建一个函数get_start_time&amp; get_end_time从数据库中获取数据

在视图上: - 只需在控制器中调用变量define: -

<script>
    $(function(){
        $('#js-countDown').yuukCountDown({
            starttime: '<?php echo $start_time; ?>',
            endtime: '<?php echo $end_time; ?>',
            notStartCallBack: function(time){
                console.log("Ready");
            },
            startCallBack: function(time){
                console.log("Running");
            },
            endCallBack: function(time){
                console.log("Complete");
            }
        });

    });
</script>