POST变量不';在AJAX被用于过滤选择选项之后不存在


POST variable doesn't exist after AJAX is used to filter select options

我有一个使用POST方法的工作表单,该表单包含以下选择下拉列表:

<div id="typeselect">
<select name="type" id="type" style="float:left;margin-right:100px;">
<option>Choose Surgery type</option>
<?php
$spec_res=mysql_query("select * from operation_list order by Narrative") or die(mysql_error());
while($spec_row=mysql_fetch_array($spec_res)){
    echo "<option>".$spec_row['Narrative']."</option>";
}
?>
</select>
</div>

它运行良好,在操作页面上,$_POST['type']具有所选内容的正确值。

但是,我添加了另一个带有id='specialty'的下拉列表,用于使用Ajax动态筛选"type"下拉列表中可用的选项。筛选基于同一个"operation_list"数据库表中名为"Specialty1"的列。这也有效,但当我提交表单时,$_POST['type']没有值!有人能告诉我我做错了什么吗?以下是Ajax函数及其指向的PHP文件:

<script type="text/javascript">
function getTypes(str)
{
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("typeselect").innerHTML=xmlhttp.responseText; 
    }
  }
xmlhttp.open("GET","showtypes.php?specialty="+str,true);
xmlhttp.send();
}
</script>

和showtypes.hp:

<?php
//dbconnection here
$specialty=$_GET['specialty'];
?>
<select name="type" id="type" style="float:left;margin-right:100px;">
<option>Choose Surgery type</option>
<?php
$spec_res=mysql_query("select * from operation_list where Specialty1='$specialty' order by Narrative") or die(mysql_error());
while($spec_row=mysql_fetch_array($spec_res)){
    echo "<option>".$spec_row['Narrative']."</option>";
}
?>
</select>

总之,在我使用Ajax更改选择选项后,为什么$_POST['type']不存在呢?在保留所有功能的同时,我能做些什么来解决这个问题?

EDIT:别介意Ajax函数中的注释,它已经过时了,我忘了删除它。

我不知道你的问题是什么,但我认为如果你使用jQuery,你可以简化它。

<script type="text/javascript">
    $('#type').change(function() {
        $('#typeselect').load('showtypes.php', { specialty: $(this).val() });
    });
</script>
  • 请参阅http://api.jquery.com/change/以获取有关更改事件的信息
  • 请参阅http://api.jquery.com/load/以获取Ajax加载函数的信息

更好的是,

jQuery化函数:

function getTypes(str,input_form){
    $.post("showtyps.php?specialty="+str, $("#"+input_form).serialize(), 
    function(data){
        // This happens when the data is loaded
        $("#typeselect").html(data);
    });
}

不同的是,您还需要将表单的id与第一个参数一起传递。

如果你想一次只做一个字段,你可以替换

$("#"+input_form).serialize()

带有

{
    'postvariablename' : $("#idofelement").serialize(),
    'postvariable2name' : $("#idof2ndelement").serialize()
}

等等…

当然,您首先需要包含jQuery才能使其工作,但我强烈建议在这些类型的情况下使用它,以最大限度地实现交叉兼容性。