我有一个基本的HTML表单,我想填写美国各州的名字。我有50个(阿拉巴马州到怀俄明州)以下列格式存储:
<?xml version="1.0"?>
<states xml:lang="EN">
<item>
<label>Alabama</label>
<value>AL</value>
</item>
<item>
<label>Alaska</label>
<value>AK</value>
</item>
...
我为此写了一些AJAX:
function ajaxFunction(str) {
if (str.length==0) {
document.getElementById("search").innerHTML="";
document.getElementById("search").style.border="0px";
return;
}
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState==4 && ajaxRequest.status==200) {
document.getElementById("search").innerHTML=ajaxRequest.responseText;
document.getElementById("search").style.border="1px solid #A5ACB2";
}
}
ajaxRequest.open("GET","USA_States.xml",true);
ajaxRequest.send();
}
HTML:
<form id = "form1">
<input onkeyup="ajaxFunction(this.value);" type = "text" size = "30" id = "text1" autocomplete="off"/>
<div id = "search">
它仍然不起作用。建议?我做错了什么?
答案 0 :(得分:1)
你可能正在寻找这个。用这个替换你的javascript代码。
function ajaxFunction(str) {
if (str.length==0) {
document.getElementById("search").innerHTML="";
document.getElementById("search").style.border="0px";
return;
}
var input=document.getElementById('text1').value;
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState==4 && ajaxRequest.status==200) {
var res=ajaxRequest.responseXML;
var states=res.getElementsByTagName("states");
var elem=states[0];
var items=res.getElementsByTagName("item");
document.getElementById("search").innerHTML="";
for(var i=0;i<items.length;i++){
var item=items[i].getElementsByTagName("label");
var state=item[0].innerHTML;
var len=str.length;
var match=state.substr(0,len);
if(match.toUpperCase()==input.toUpperCase()){
var val=items[i].getElementsByTagName("value");
var value=val[0].innerHTML;
var e = document.createElement('span');
e.innerHTML = state+"("+value+") ";
document.getElementById("search").appendChild(e.firstChild);
}
}
document.getElementById("search").style.border="1px solid #A5ACB2";
}
}
ajaxRequest.open("GET","USA_States.xml",true);
ajaxRequest.send();
}