参考标题。我有一个我编码的数组: -
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result)) {
$dServer[] = $row['model'];
}
现在,如何将 $ dServer 数组传递给Javascript数组?
例如,这个数组:
var a = new Array();
答案 0 :(得分:15)
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result)){
$dServer[] = $row['model'];
}
?>
<script type="text/javascript">
var a = <?php echo json_encode($dServer); ?>;
</script>
答案 1 :(得分:3)
将其编码为json对象。
<?
$arr = array('entry' => 'content');
?>
<script>
var data = <?=json_encode($arr);?>;
alert(data['entry']);
</script>
答案 2 :(得分:1)
尝试使用ajax请求和json_encode。
第二个变种
<?php
$query = "SELECT * FROM server";
$result = mysql_query($query);
$dServer = array();
while($row = mysql_fetch_assoc($result))
{
$dServer[] = $row['model'];
}
?>
var a = <?php echo json_encode($dServer);?>;
答案 3 :(得分:1)
除了提到的ajax / json方法,您还可以直接打印出值:
<?php
$query = "SELECT * FROM server";
$result = mysql_query($query);
?>
<script type="text/javascript">
var a = new Array();
<?php
while($row = mysql_fetch_assoc($result)){
echo "a['model'] = " . $row['model'] . ";";
echo "a['nextField'] = " . $row['nextField'] . ";";
}
?>
</script>