我正在尝试使用ajax和php实现一个动态下拉列表。根据第一个选项列表中的索引值,第二个选项应该为我提供具有该id的名称列表。
选择1.php:
<html>
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch1.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Dynamic Select Option Menu Using Ajax and PHP</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select ID</option>
<?php
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select distinct id from test";
$select= $conn->query($sql);
if ($select->num_rows > 0) {
while($row = $select->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['id']."</option>";
//echo "<option value=>".$row['id']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
<select id="new_select">
</select>
</div>
</center>
</body>
</html>
获取1.php
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['get_option'];
//echo '$id';
$sql = "select id, name from test where id='$id'";;
$find= $conn->query($sql);
if ($find->num_rows > 0) {
while($row = $find->fetch_assoc()) {
//echo "<option>".$row['name']."</option>";
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
} else {
echo "0 results";
}
exit;
}
?>
我的数据库如下所示:
SELECT * from test;
id name
1 Name1
2 Name2
1 Name3
第一个下拉列表工作正常。但是第二个下拉列表不起作用。我也附上了它的截图。跨文件发送数据有问题吗?不知道代码哪里出错了。
对于第二个选项列表,当我选择1时,我应该得到name1和name3作为选项,但是我没有得到任何选项。
编辑:select1.php中更正的javascript
2条答案
按热度按时间hxzsmxv21#
为selectbox中的选项添加值,现在没有从fetch\u select()传递值
zpjtge222#
您正在为设置内容
new_select
使用错误的变量。应该是的
response
而不是val
更改为:并为返回选项赋值。
比如:
并将您的sql字符串更改为以下内容,以使上述操作正常工作。
确保你的
jquery.js
正在加载include。