学习JavaScript的时候,学到了Ajax的部分,觉得它很有意思,便照着书上的例子写了一个最简单的Ajax的HelloWorld的例子。Ajax是“Asynchronous JavaScript and XML”的意思,即(异步JavaScript和XML),通常用来实现网页中局部的刷新,我们看到看到的谷歌地图,谷歌建议都是Ajax技术。

首先写一下服务器端的后台xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<HelloWorld>
<data>
我是后台的HelloWorld!
</data>
</HelloWorld>

接下是前台的html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.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>Insert title here</title>
<script type="text/javascript">
var xmlHttp;
//创建XMLHttpRequest对象的方法
function createXmlHttpRequest()
{
if(window.ActiveXObject)//针对IE浏览器
{
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");//针对IE高版本
}
catch(e){
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//针对IE低版本
}
}
else if(window.XMLHttpRequest)//针对非IE浏览器
{
xmlHttp = new XMLHttpRequest();
}
xmlHttp.onreadystatechange = readyStateChangeHandle;
xmlHttp.open("GET","HelloWorld.xml",true);
xmlHttp.send(null);
}

function readyStateChangeHandle()
{ //读取服务器的状态
if(xmlHttp.readyState == 4)
{ //判断服务器状态码,如果服务器端没有错误返回200
if(xmlHttp.status == 200)
{
var div = document.getElementById("div1");
//接收服务器响应的xml文档
var xmlDoc = xmlHttp.responseXML;
//解析服务器响应的XML文档
var data = xmlDoc.getElementsByTagName("data")[0].firstChild.nodeValue;
div.innerHTML = "<b>"+data+"</b>";
}
}
}
</script>
</head>
<body>
<div align="center" id="div1" style="width:100%"></div>
<div align="center" style="width:100%">
<input type="button" value="Hello World" id="btnRequest" onclick="createXmlHttpRequest()">
</div>
</body>
</html>

 单击网页中的HelloWorld按钮,结果如下所示: