我是jQuery的新手,遇到一个问题,我无法发布源自依赖动态下拉列表的值。
这是我写的代码:
的index.php
<form name="form1" action="test.php" method="post">
<table>
<tr>
<td>
<select id="branddd" onchange="change_brand()" required>
<option disabled="disabled" selected="selected" style="color:gray" required >brand</option>
<?php
$res=mysqli_query($link,"select * from brand");
while($row=mysqli_fetch_array($res))
{
?>
<option name="brand" value="<?php echo $row["id"];?>"><?php echo $row["name"];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>
<div id="model">
<select name="model">
<option required>model</option>
</select>
</td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
这是我编写的用于将数据从MySQL加载到第二个下拉框中的JavaScript:
<script type="text/javascript">
function change_brand()
{
var xmlhttp=new XMLHttpRequest () ;
xmlhttp.open("GET","ajax.php? brand="+document.getElementById("branddd").value,false) ;
xmlhttp.send(null) ;
document.getElementById("model").innerHTML=xmlhttp.responseText ;
}
</script>
ajax.php :
<?php
$link=mysqli_connect("localhost","root","");
mysqli_select_db($link,"test_db");
$brand=$_GET["brand"];
if($brand!="")
{
$res=mysqli_query($link,"select * from model where brand_id=$brand");
echo "<select>";
while($row=mysqli_fetch_array($res))
{
echo "<option>"; echo $row["name"]; echo "</option>";
}
echo "</select>";
}
?>
答案 0 :(得分:1)
在select[id="branddd"]
中添加名称属性,并将name="brand"
添加到select tag
,而不是options
中,
<select id="branddd" name="brand" ...
检查您的select[name="model"]
后div是否已关闭。并将required
添加到选择框而不是option
在服务器端,您无需再次回复<select>
,只需尝试此操作,
while($row=mysqli_fetch_array($res))
{
echo "<option>".$row["name"]."</option>";
}
将ID添加到select
而不是div
如果您使用的是jquery,那么您的onchange事件可能很短,如
$(function(){
$('#branddd').on('change',function(){
this.value && // if value!="" then call ajax
$.get('ajax.php',{brand:this.value},function(response){
$('select[name="model"]').html(response);
});
});
});
如果使用jquery,您必须从onchange
移除<select id="branddd" onchange="change_brand()" required>
,就像<select id="branddd" required>