我试图在启动时从 javascript 填充选择框,每个框都取决于前一个框。
在 HTML 代码中我有
<body onload="start_up()">
<span id="FirstList">xxxxxxx</span>
<span id="SecondList">xxxxxxx</span>
Javascript代码是
function start_up()
{
load_select('','Type1')
load_select(document.getElementById('select_first').value,'Type2')
}
function load_select(argument,code)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getdropdown.php";
url=url+"?q="+code+argument;
url=url+"&sid="+Math.random(); // this is needed to make sure its not loading a cached version
last_http_type=code;
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
if (last_http_type=="Type1")
document.getElementById("FirstList").innerHTML=xmlhttp.responseText;
else if (last_http_type=="Type2")
document.getElementById("SecondList").innerHTML=xmlhttp.responseText;
else if (last_http_type=="Type3")
document.getElementById("OutputTable").innerHTML=xmlhttp.responseText;
else if (last_http_type=="Type4")
document.getElementById("OutputTable").innerHTML=xmlhttp.responseText;
last_http_type="cleared";
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
if (window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
return null;
}
当它们的代码在 php 中生成时,选择框被命名为 select_first 和 select_second。
这适用于第一个,但第二个 load_select 失败,因为它不知道 select_first。我假设它是按顺序完成的,因此,当它到达语句时,应该知道第一个下拉菜单。(请注意,为了说明问题,上面的代码稍微简化了一点,load_select 的第二个参数确定了确切的 SQL 调用,而且 stateChanged 稍微复杂一些,因为它需要知道调用了哪个 load_select。但是,它们都可以正常工作他们自己,它在启动时的多重负载失败了。)