使用php变量填充javascript数组

时间:2018-01-31 13:26:28

标签: javascript php arrays

我想用我的php变量$jaar填充javascript数组。但是当我在js文件中打印它时,我得不到正确的输出。

php文件

<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
    while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
        $jaar .= "\"" . $row[0] . "\""; 
        $jaar .= ",";
    }
$jaar{ strlen($jaar)-1 } = ']';

echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";

?>
<script src="js/calender.js"></script>

js文件

//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]

//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want

1 个答案:

答案 0 :(得分:5)

需要进行一些更改:

while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
    // create $jaar[]
    $jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php

了解更多: