我在数据库中创建了一个表(test)。 现在我已经在这样的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数组的正确方法。
答案 0 :(得分: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 '];';
答案 1 :(得分:1)
<?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>
答案 2 :(得分:0)
这样:
var images=["<?php echo $row[0]; ?>", "<?php echo $row[1]; ?>" ... and so on]
答案 3 :(得分: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>
使用计数器跟踪您要添加新项目的位置。