日期:2014-05-16  浏览次数:21010 次

Ajax不错的简单入门实例(转载)
这个是用于显示主体的ajax.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>AJAX网页开发实例</title>

<script type="text/javascript"><!--
function ajaxRead(file){
var xmlObj = null;
if(window.XMLHttpRequest){
xmlObj = new XMLHttpRequest();
} else if(window.ActiveXObject){
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return;
}
xmlObj.onreadystatechange = function(){
if(xmlObj.readyState == 4){
updateObj('xmlObj', xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
}
}
xmlObj.open ('GET', file, true);
xmlObj.send ('');
}
function updateObj(obj, data){
document.getElementById(obj).firstChild.data = data;
}
//--></script>

</head>
<body>
<h1>AJAX网页开发实例</h1>
<p>看看下面的例子,你也许就会懂得数据是怎么样完成无刷新的了。</p>
<p id="xmlObj" style="border:1px dashed #ccc;padding:10px;">
这是一些简单的数据。<a href="data.xml" title="调取XML数据。 " onclick="ajaxRead('data.xml'); this.style.display='none'; return false">调取XML数据。 </a>
</p>
<p><a href="http://www.b3inside.com">返回Blog</a></p>
</body>
</html>

下面是包含数据的data.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<data>
这里是XML中的数据。
</data>
</root>

注意我们现在连接data.xml并没有使用javascript,要使用javascript,执行ajaxRead函数,连接是隐藏的,并且此连接并没有重定向到data.xml文件。函数ajaxRead还没有定义,所以当你测试时,会得到一个JS错误。所以我们在开始的<head>中定义了函数:
<script type="text/javascript"><!--
function ajaxRead(file){
var xmlObj = null;
if(window.XMLHttpRequest){
xmlObj = new XMLHttpRequest();
} else if(window.ActiveXObject){
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return;
}
xmlObj.onreadystatechange = function(){
if(xmlObj.readyState == 4){
updateObj('xmlObj', xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
}
}
xmlObj.open ('GET', file, true);
xmlObj.send ('');
}
function updateObj(obj, data){
document.getElementById(obj).firstChild.data = data;
}
//--></script>

解释下,函数ajaxRead将在点击View XML data连接的时候执行,在函数里,我们定义了一个xmlObj的变量,它就负责客户端和服务器端中转。我们定义一个if/else循环块:
if(window.XMLHttpRequest){
xmlObj = new XMLHttpRequest();
} else if(window.ActiveXObject){
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return;
}

这只是测试不同对象的可用性——不同的浏览器执行XMLHttpRequest对象的时候不同,所以我们定义“xmlObj”作为XMLHttpRequest对象的时候,我们必须区别对待。如果没有XMLHttpRequest可用,函数以return结束来取消错误报告。大部分时候,XMLHttpRequest都是可用的,不过排除一些太老的浏览器。

下面的部分:
xmlObj.onreadystatechange = function(){
if(xmlObj.readyState == 4){
updateObj('xmlObj', xmlObj.responseXML.getElementsByTagName('data')[0].firstChild.data);
}
}

每当XMLHttpRequest状态改变时,onreadystatechange事件就触发,此事件共有5个状态,从0到4。
[0]uninitialized未初始化(在XMLHttpRequest开始前)
[1]loading(一旦初始化)
[2]loaded(一旦XMLHttpRequest从服务器端获得响应)
[3]interactive(当对象连接到服务器)
[4]complete(完成)
状态5[编号是4]是用来确认数据是否可用的,正好用来给xmlObj.readyState用,如果“是”,我们执行updateObj函数,此函数有2个参数:ID以及填充的数据,它的方法以后说明。

?