我想用我的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

最佳答案

需要进行一些更改:

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

阅读更多:
  • json_encode()
  • 09-30 19:33