我想我必须扩展上一个问题:
我有一个mySql查询,然后从数据中创建一个数组。使用数组中的值,将创建表单的下拉列表。然后从php数组创建一个javascript数组。并且onchange()函数正在尝试使用下拉列表选择(dropd.value)中的ID值作为数组中的键来更改字段中的图像(以显示图像名称)。
<?PHP
include 'open_connection_con.php';
$prod_query = mysqli_query($con,"SELECT id, type, image_name, description FROM Products");
$products = array();
while($row = mysqli_fetch_array($prod_query))
{
$products[] = $row;
}
// then I create a dropdown list within a form.
echo "<select name='prodType' id='prodDrop' onchange='swapProd()'>";
echo "<option value='0'>Select one:</option>";
foreach ($products as $row)
{
echo "<option value='" . $row['id'] . "'>" . $row['type'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
<script type="text/javascript">
// pass the php array into a javascript array.
var prodArrJS = <?php echo json_encode($products);?>
// and the function to display the image (on <img id="prodImage">) of the selected product
from the dropdown list above
function swapProd()
{
var image = document.getElementById("prodImage");
var dropd = document.getElementById("prodDrop");
image.src = "images/ex/" + prodArrJS[dropd.value][2] + ".jpg";
var p1=document.getElementById("lar");
p1.value="x"
}
</script>
<?php
unset( $products );
?>
不显示功能结束时的图像(不显示任何内容,甚至不显示小问号),功能停止。 我用数字和字符串测试了数组,它运行正常。