我在cat.php
文件中有以下代码:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsub.php?q="+str,true);
xmlhttp.send();
}
</script>
<select name="users" onchange="showUser(this.value)">
<option value=""></option>
<?php
$query = "SELECT cat from category GROUP BY cat";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num=mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row=mysql_fetch_assoc($result);
echo "<option value=''>".$row['cat']."</option>";
}
echo "</select>";
<div id="txtHint"></div>
在调用函数后 - getsub.php
<?php
require_once('connect_db.php');
//get the q parameter from URL
$q=$_GET["q"];
$query = "SELECT sub from category WHERE cat = '".$q."'";
$result = mysql_query($query);
if(!$result){
mysqli_error();
}
while ($row = mysql_fetch_assoc($result)){
?>
<select name="sub">
<?php
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
echo "<option value='".$row['sub']."'>".$row['sub']."</option>";
}
?>
<select>
<?php
}
我期待主要类别和子类别之间存在关联。我想选择主类别,然后调用javascript函数以显示子类别的另一个选择输入。上面的代码没有输出,我似乎无法找到原因?
请帮助
答案 0 :(得分:0)
代码看起来很好。尝试使用Firefox的firebug扩展。 在firebug中打开网络面板,然后查看您发送的数据以及实际生成的响应。 这肯定会有所帮助。 同样在cat.php中,而不是使用普通的AJAX,尝试使用jQuery,因为这将减少大量代码
// Just incude jQuery beforehand
script>
function showUser(str)
{
$.get("getsub.php",{q:str},function(data){
$("#txtHint).html(data);
});
}
</script>
答案 1 :(得分:0)
你的代码看起来不错,但你需要关闭while循环结尾的php标签。