<!DOCTYPE html PUBLIC "-//W3C//DTD HTML4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>AJAX_Test</title>
</head>
<body>
<form name="myForm">
输入关键字:<input type="text" name="key" onkeyup="search(this.value)"><br>
图书信息:<span id="txtHint"></span>
</form>
<script type="text/javascript">
var xmlHttp;
var key;
function search (value) {
// body...
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
alert("你的浏览器不支持AJAX!");
return false;
}
}
}
key = value;
url = "books.xml";
xmlHttp.onreadystatechange=myfunc;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function myfunc(){
if (xmlHttp.readyState==4) {
var xmlStr = xmlHttp.responseText;
xmlStr = parse(xmlStr);
document.getElementById("txtHint").innerHTML = xmlStr;
}
}
function parse(xmlStr){
var xmlDoc = null;
if(window.ActiveXObject){
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
}else if (document.implementation.createDocument()) {
xmlDoc = document.implementation.createDocument("","",null);
}else{
alert("浏览器不能处理!");
}
var tableStr = "";
if (xmlDoc!=null) {
xmlDoc.async=false;
xmlDoc.loadXML(xmlStr);
tableStr+="<table border='1'>";
var x = xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++){
var name = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var price = x[i].getElementsByTagName("price")[0].childNodes[0].nodeValue;
var author = x[i].getElementsByTagName("author")[0].childNodes[0].nodeValue;
var year = x[i].getElementsByTagName("year")[0].childNodes[0].nodeValue;
if(name.indexOf(key)==-1)continue;
tableStr+="<tr>";
tableStr+="<td>"+name+"</td>";
tableStr+="<td>"+price+"</td>";
tableStr+="<td>"+author+"</td>";
tableStr+="<td>"+year+"</td>";
tableStr+="</tr>";
}
tableStr+="</table>";
}
return tableStr;
}
</script>
</body>
</html>
上面是网页代码,输入任何关键字都没反应啊,books.xml文件是没有错的,
<?xml version="1.0" encoding="utf-8"?>
<books>
<book isbn="13452728">
<name>《水浒传》</name>
<price>80</price>
<author>施耐庵</author>
<year>元末</year>
</book>
<book isbn="78789779">
<name>《西游记》</name>
<price>90</price>
<author>吴承恩</author>
<year>明代</year>
</book>
<book isbn="36734598">
<name>《三国演义》</name>
<price>75</price>
<author>罗贯中</author>
<year>元末</year>
</book>
<book isbn="63458728">
<name>《红楼梦》</name>
<price>79</price>
<author>曹雪芹</author>
<year>清代</year>
</book>
</books>
是不是代码的问题,还是在tomcat的文件夹缺少东西?小白第一次接触AJAX,求助!