-2

我在数据库中创建了一个表(测试)。现在我已经像这样在 php 中获取数组。

 $sql="SELECT * FROM test;";
  $result=mysqli_query($con,$sql) or die("invalid query ".mysqli_error($con));
  while($row=mysqli_fetch_array($result))
  {
    echo $row['name'];
  }

现在我想将此数组传递给 javascript 数组。

var images=["$row[0]","$row[1]","$row[2]"];// Is that coreect way to pass php array into js array?

如果不是将 php 数组传递给 javascript 数组的正确方法。

4

4 回答 4

2
<?php
$mysqli = new mysqli("localhost", "username", "password", "database_name");

$query = "SELECT * FROM test;";
$result = $mysqli->query($query);

while($row = $result->fetch_array())
{
    $rows[] = $row;
}
?>

<script>
    var images = [<?=implode(',', $rows);?>];
</script>
于 2013-03-20T07:49:46.187 回答
1
$sql="SELECT * FROM test;";
$result=mysqli_query($con,$sql) or die("invalid query ".mysqli_error($con));
print 'var images=[';
$tmp = array();
while($row=mysqli_fetch_array($result))
{
   $tmp[] = '"'.$row['name'].'"';
}
print implode(',', $tmp);
print '];';
于 2013-03-20T07:45:29.680 回答
0

这边走:

var images=["<?php echo $row[0]; ?>", "<?php echo $row[1]; ?>" ... and so on]
于 2013-03-20T07:43:01.497 回答
0

您需要在 javascript 中回显您的变量,例如:

<?php
     $sql="SELECT * FROM test;";
     $result=mysqli_query($con,$sql) or die("invalid query ".mysqli_error($con));
     $counter = 0;
?>

<script>
var images=new Array();
<?php
    while($row=mysqli_fetch_array($result))
    {
         echo 'images['.$counter.']="'.$row['name'].'";'
         $counter++;
    }
?>
</script>

使用计数器来跟踪您要添加新项目的位置。

于 2013-03-20T07:50:51.423 回答