gpt4 book ai didi

javascript - 选择选项后自动显示数据库值

转载 作者:行者123 更新时间:2023-11-28 05:48:45 26 4
gpt4 key购买 nike

假设我有这样的 SQLite 数据库:

+----+-----------+-------+
| id | name | price |
+----+-----------+-------+
| C1 | Car | 50000 |
| B1 | Bike | 1500 |
| M1 | Motorbike | 15000 |
| T1 | Truck | 99000 |
+----+-----------+-------+

然后为了向选择表单显示数据库,我使用以下代码:

<form method="post" action="action.php">
<table>
<tr>
<td>Vehicle</td>
<td>:</td>
<td>
<select name='id_vh' onchange='OnChange(this.value)' required>
<option selected value=''>choose</option>
<?php
$sql="SELECT * FROM vehicle ORDER BY name ASC";
$result=$db->query($sql);
$row=$result->fetchall(PDO::FETCH_ASSOC);
foreach($row as $dt){
echo "<option value='$dt[id]'>$dt[name]</option>";}
?>
</select>
</td>
</tr>

如何在选择选项后自动显示价格,我使用这样的代码但不起作用:

<tr>
<td>Price</td>
<td>:</td>
<?php
if(isset($_POST['id_vh'])){
$idv=$_POST['id_vh'];
$query=$db->prepare("SELECT * FROM price WHERE id = '$idv'");
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
echo"<td>$result[price]</td>";
}
?>
</tr>
</table>
</form>

最佳答案

为要处理的表单设置一个 ID

<form id="vehicleForm" method="post" action="action.php">
<table>
<tr>
<td>Vehicle</td>
<td>:</td>
<td>

为您的选择器设置一个 ID 来处理

<select id='id_vh' name='id_vh' required>
<option selected value=''>choose</option>
<?php
$sql="SELECT * FROM vehicle ORDER BY name ASC";
$result=$db->query($sql);
$row=$result->fetchall(PDO::FETCH_ASSOC);
foreach($row as $dt){
echo "<option value='$dt[id]'>$dt[name]</option>";}
?>
</select>
</td>
</tr>

添加 jquery 文件

<script type="text/javascript" src="/js/jquery.min.js"></script>

添加一个函数来拦截变化

<script Type="text/javascript">
$('#id_vh').on("change",(function (e) {
/*just for debugging*/
alert( this.selectedOptions[0].value);
/*submit the Form*/
vehicleForm.submit();
}));
</script>

这应该有效。 $_POST 现在将包含 id_vh 的值

关于javascript - 选择选项后自动显示数据库值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38262692/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com