看了一个例子,敲了一遍。运行一看,结果效果出不来,还报错:
仔细看了看代码,还真有地方敲错了。修正后继续运行,还是报这个错。然后又看了一遍代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title> 动态编辑页面内容</title>
<script language="javascript">
var xmlHttp;
// xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
function process(){
xmlHttp.open("GET","pg.xml",true);
xmlHttp.onreadystatechange=handle_f;
xmlHttp.send(null);
}
function handle_f(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
clearpreviousr();
parser();
}else{
alert("执行过程中出现问题,服务器返回"+xmlHttp.statusText);
}
}
}
function clearpreviousr(){
var header=document.getElementsByTagName("header");
if(header.hasChildNodes){
header.removeChild(header.ChildNodes[0]);
}
var tablebody=document.getElementById("resultbody");
while(tablebody.childNodes.length>0){
tablebody.removeChild(tablebody.ChildNodes[0]);
}
}
function parser(){
var result=xmlHttp.responseXML;
var wood=null;
var name="";
var cost="";
var number="";
var woods=result.getElementsByTagName("wood");
for(var i=0;i<woods.length;i++){
wood=woods[i];
name=wood.getElementsByTagName("name")[0].firstChild.nodeValue;
cost=wood.getElementsByTagName("cost")[0].firstChild.nodeValue;
number=wood.getElementsByTagName("number")[0].firstChild.nodeValue;
addtablerow(name,cost,number);
}
document.getElementById("resulttable").setAttribute("border","1");
}
function addtablerow(name,cost,number){
var row=document.createElement("tr");
var cell=document.createElement("td");
var textNode=document.createTextNode(name);
cell.appendChild(textNode);
row.appendChild(cell);
var cell=document.createElement("td");
var textNode=document.createTextNode("cost");
cell.appendChild(textNode);
row.appendChild(cell);
var cell=document.createElement("td");
var textNode=document.createTextNode(number);
cell.appendChild(textNode);
row.appendChild(cell)
document.getElementById("resultbody").appendChild(row);
}
</script>
</head>
<body>
<h1>为页面动态添加内容</h1>
<input type="button" value="显示内容" onclick="process()" />
<p>
<span id="header"></span>
<p>
<table id="resulttable">
<tbody id="resultbody"></tbody>
</table>
</body>
</html>
发现不出什么错误。想了半天,发现自己是直接运行的html文件,而ajax的核心是XmlHttpRequest,他要向服务器提出请求并处理响应,因此,需要在一个服务器下运行ajax,才能看到其效果。看来得继续学习ajax。