gpt4 book ai didi

javascript - AJAX PHP+MySQL - 选择框

转载 作者:行者123 更新时间:2023-11-29 12:56:50 24 4
gpt4 key购买 nike

所以我有一个我想要修改的简单AJAX示例,所以当我更改选择框中的年份时,我希望它对多个div生效,而不仅仅是具有ID的div。有什么解决办法吗?我正在考虑 getelementsbyclassname,但它没有显示任何内容。

<html>
<head>
<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","proba.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onChange="showUser(this.value)">
<option value="">Choose year:</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
</select>
</form>
<br>

<div id="txtHint"><b> - </b></div>

<p>&nbsp;</p>
</body>
</html>

最佳答案

getElementsByClassName 工作得很好,你只需要迭代返回的项目:

<html>
<head>
<script>
function showUser(str) {
if (str=="") {
setContent("");
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) {

setContent(xmlhttp.responseText);

}
}
xmlhttp.open("GET","proba.php?q="+str,true);
xmlhttp.send();
}

function setContent(content){
var divs = document.getElementsByClassName('txtHint'); //fixed syntax error here
var i = divs.length;

while(i--) {
divs[i].innerHTML = content;
}
}
</script>
</head>
<body>

<form>
<select name="users" onChange="showUser(this.value)">
<option value="">Choose year:</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
</select>
</form>
<br>

<div class="txtHint"><b> - </b></div>
<div class="txtHint"><b> - </b></div>
<div class="txtHint"><b> - </b></div>

<p>&nbsp;</p>
</body>
</html>

关于javascript - AJAX PHP+MySQL - 选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23932867/

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