gpt4 book ai didi

php - 如何使用 AJAX 更新选择菜单 w/out
inside form

转载 作者:可可西里 更新时间:2023-10-31 23:50:38 24 4
gpt4 key购买 nike

我正在使用 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>

最佳答案

试试这个:

if (req.status == 200) {
var selects = document.getElementsByTagName("select");
for(var i=0;i<selects.length;i++) {
var s = selects[i];
if(s.name == "county") {
var replacement = document.createElement("div");
replacement.innerHTML = req.responseText;
s.parentNode.insertBefore(s,replacement);
s.parentNode.removeNode(s);
break;
}
}
//document.getElementById('countydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}

关于php - 如何使用 AJAX 更新选择菜单 w/out <div> inside form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2304543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com