AJAX基础例子
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>HelloAjax.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
window.onload = initAll;
var xhr = false;
var c = 0;
function initAll(){
timedCount();
document.getElementById("one").onclick = getFile;
document.getElementById("two").onclick = getFile;
}
function timedCount(){
document.getElementById('txt').innerHTML = c;
c = c+1;
setTimeout("timedCount()",1000);
}
function getFile(){
makeRequest(this.href);
return false;
}
function makeRequest(url){
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
if(window.ActiveXObject){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
}
}
}
if(xhr){
xhr.onreadystatechange = showFile;
xhr.open("GET",url,true);
xhr.setRequestHeader('If-Modified-since','Thu,06 Apr 2006 01:00:00 GMT');
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(null);
}else{
document.getElementById("fileArea").innerHTML = "couldn't create an XMLHttpRequest!";
}
}
function showFile(){
var outMsg = "";
if(xhr.readyState == 1){
var outMsg = 'loading...';
document.getElementById("fileArea").innerHTML = outMsg;
}
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseXML.getElementsByTagName("bookname");
if(data.length>0){
var outMsg = "xml:";
for(i = 0;i<data.length; i++){
outMsg = outMsg +data[i].firstChild.nodeValue;
}
}else{
var outMst = "text:";
outMsg = outMsg + xhr.responseText;
}
}
}
document.getElementById("fileArea").innerHTML = outMsg;
}
</script>
</head>
<body>
<div id = "txt"></div><br/>
<a id = "one" href = "data/one.txt">one text</a><br/>
<a id = "two" href = "data/two.txt">two text</a><br/>
<div id = "fileArea"></div>
</body>
</html>
------------------------------------------
data文件夹下的one.txt文件
one
one
one
one
data文件夹下的two.txt文件
<? xml version = "1.0" ? >
<books>
<bookname>java 1</bookname>
<bookname>java 2</bookname>
</books>