Php 动态下拉列表不工作
我正在尝试使用Ajax和PHP实现一个动态下拉列表。根据第一个选项列表中的索引值,第二个选项应该为我提供具有该id的名称列表 选择1.php:Php 动态下拉列表不工作,php,html,mysql,ajax,Php,Html,Mysql,Ajax,我正在尝试使用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
<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时,我应该得到Name1和Name3作为选项,但我没有得到任何选项
编辑:更正了select1.php中的javascript您正在使用错误的变量设置
new\u select
的内容
它应该是response
而不是val
改为:
document.getElementById("new_select").innerHTML=response;
并为您的返回选项赋值
如:
echo "<option value='".$row['id']."'>".$row['name']."</option>";
并确保您的
jquery.js
include正在加载。为选择框中的选项添加值,此时没有从fetch_select()传递的值。
没有值
。将您的响应作为HTML选项标记,然后将该响应填充到第二个选择框中;如果您有任何疑问,只需使用警告声明,这样您就可以确认您得到的是正确的值。这三个选项都不起作用。还添加了,echo“$row['id']”
在select1.php
中刚刚完成。你能检查一下吗?在fetch1.php中添加-ini\u集('display\u errors',1)代码>和错误报告(E_ALL)代码>位于文档顶部。请确保已加载jquery.js include。非常感谢。现在可以了。我真蠢,竟然不检查.js文件。
document.getElementById("new_select").innerHTML=response;
echo "<option value='".$row['id']."'>".$row['name']."</option>";
$sql = "select id, name from test where id='$id'";