5

参考标题。我有一个这样编码的数组:-

$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();
4

4 回答 4

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>
于 2012-04-19T02:01:56.083 回答
3

将其编码为 json 对象。

<?
    $arr = array('entry' => 'content');
?>

<script>
var data = <?=json_encode($arr);?>;
alert(data['entry']);
</script>
于 2012-04-19T02:01:11.463 回答
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);?>;
于 2012-04-19T02:00:38.253 回答
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>
于 2012-04-19T02:46:47.580 回答