一个简单的Ajax应用

我在上一篇文章中写了在asp中如何用Ajax技术免重载网页检查用户名是否被占用,那么这篇博文主要通过一个简单的Ajax应用来解析一下Ajax技术的原理。

首先需要三个文件,simpleAjax.hml(用来看效果),simpleAjax.js(用JavaScript中的XMLHttpRequest对象来直接与服务器进行通信),simpleAjax.txt(可以自定义异步通信输出内容的文件)。

一、新建simpleAjax.html文件

index.html
<html>
	<head>
		<title>一个简单的Ajax应用</title>
		<script type="text/javascript" src="simpleAjax.js"></script>
	</head>
	<body>
		<input type="button" value="Ajax请求" onclick="startrequest()"/>
		<div id="responseResult"></div>  <!--节点responseResult将在simpleAjax.js中被使用,最后输出simplAjax.txt中的文字-->
	</body>
</html>

二、新建simpleAjax.js文件

javascript.javascript
var xmlhttp=null;//首先创建一个作为 XMLHttpRequest 对象使用的 xmlhttp 变量,值设为 null
function createXMLHttpRequest(){
	if (window.XMLHttpRequest){
		xmlhttp=new XMLHttpRequest();//针对 IE7+, Firefox, Chrome, Opera, Safari
  	}
  	else if (window.ActiveXObject){
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//针对 IE6, IE5
  	}
}

//由simpleajax.html中的按钮点击调用这个函数
function startrequest(){
	createXMLHttpRequest();//调用上面createXMLHttpRequest()函数
	xmlhttp.onreadystatechange=handlestatechange;//调用下面handlestatechange()函数
	xmlhttp.open("GET","simpleAjax.txt",true);
	xmlhttp.send();
}

function handlestatechange(){
	if (xmlhttp.readyState==4 && xmlhttp.status==200){
		document.getElementById("responseResult").innerHTML=xmlhttp.responseText;
	}
}

名称解释:

text.text
第一个函数 createXMLHttp() 的作用是根据客服端浏览器类型(IE和非IE)以及IE中安装的JavaScript技术版本的不同创建不同的XMLHttpRequest对象。XMLHttpRequest对象用于在后台与服务器交换数据。它能够:在不重新加载页面的情况下更新网页、在页面已加载后从服务器请求数据、在页面已加载后从服务器接收数据、在后台向服务器发送数据。

其中 xmlhttp.onreadystatechange 表示每当存有xmlhttprequest的状态信息的readyState改变时,就会触发 这个onreadystatechange 事件。当 readyState 等于 4 且状态为 200 时,表示响应已就绪。

其中 xmlhttp:open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword) 表示创建一个新的http请求(bstrUrl),并指定此请求的方法(get,post)、URL以及varAsync布尔型,指定此请求是否为异步方式,默认为true即当状态改变时会调用onreadystatechange属性指定的回调函数。

其中 xmlhttp.send() 表示发送请求到http服务器并接收回应。

三、新建simpleajax.txt文件

任意在这个txt文件里面写入内容,例如: hello,i have changed myself! 。

四、延展:simpleAjax.js的另一种形式(结果一样)

javascript.javascript
var xmlhttp=null;//首先创建一个作为 XMLHttpRequest 对象使用的 XMLHttp 变量,值设为 null
function startrequest(){
	if (window.XMLHttpRequest){//针对 IE7+, Firefox, Chrome, Opera, Safari
  		xmlhttp=new XMLHttpRequest();
  	}
  	else{// 针对 IE6, IE5
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}
  	xmlhttp.onreadystatechange=function(){
  		if (xmlhttp.readyState==4 && xmlhttp.status==200){
    		document.getElementById("responseResult").innerHTML=xmlhttp.responseText;
    	}
  	}
  	xmlhttp.open("GET","simpleAjax.txt",true);
  	xmlhttp.send();
}

五、相关截图

一个简单的Ajaxing用-1

一个简单的Ajax应用-2

评论

评论加载中…