简体   繁体   English

我们如何在 php 的帮助下从 mysql 数据库中分配 javascript 数组?

[英]how can we assign a javascript array from mysql database with the help of php?

I would like to know if we can select data from the database using php and assign it to a javascript array?我想知道我们是否可以使用 php 将数据库中的 select 数据分配给 javascript 数组? if so what would be the syntax?如果是这样,语法是什么?

I wrote the code below but it is not working我写了下面的代码,但它不起作用

$js_array = "[";
$result = mysql_query("SELECT item_name FROM tbl_item");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
    $js_array .= $row[0]; 
    $js_array .= ",";
}
$js_array{ strlen($js_array)-1 } = ']';

 ?>

<script>
var cities = <?php echo  $js_array; ?>
for(var i=0; i<4;i++)
alert(cities.length);

</script> 

The simplest approach is converting to JSON with json_encode :最简单的方法是使用json_encode转换为JSON

// with $js_array being a true array
var cities = <?php echo json_encode($js_array)?>;

Note, that there are esoteric cases , where this solution might not work.请注意,在某些深奥的情况下,此解决方案可能不起作用。 On the other hand, the advantage is, that json_encode takes over all quoting needs.另一方面,优点是 json_encode 接管了所有引用需求。

You should not echo the array object.您不应回显数组 object。

Iterate the array and echo the value.迭代数组并回显该值。

<?php foreach( $js_array as $value) echo "'$value',"; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM