我正在使用 ajax 调用来更新选择菜单。ajax 调用通过从不同的 .php 文件运行将列表放入我的选择菜单中。
这是 JS 插入片段:
if (req.status == 200) {
document.getElementById('countydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
这是HTML:
<label for="county">County:</label>
<div id="countydiv">
<select name="county">
<option>Select State First</option>
</select>
</div>
很容易。该脚本有效,但仅当其中<div id="countydiv">
存在时。
如何将 JavaScript 更改为仍然可以使用看起来像这样的标记?
<label for="county">County:</label>
<select name="county">
<option>Select State First</option>
</select>
更新:也许我应该包括整个功能:
function getCounty(stateId) {
var strURL="findCounty.php?state="+stateId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('countydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
和标记:
<p>
<label for="state">State:</label>
<select name="state" onChange="getCounty(this.value)">
<option>Select State...</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</p>
<p>
<label for="county">County:</label>
<select name="county">
<option>Select State First</option>
</select>
</p>