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

封装第一个ajax
本文所用程序来自《Ajax模式与最佳实践》
1、由于不同的浏览器创建XMLHttpRequest对象的方式不一样,所以有必要对XMLHttpRequest对象的创建进行封装。使用工程方法模式:
factory.js中的XMLHttpRequest对象创建的代码如下
function FactoryXMLHttpRequest(){
	// 除了Microsoft的IE,其他的浏览器都能返回XMLHttpResult对象
	if(window.XMLHttpRequest){
		return new XMLHttpRequest();
	}
	else if(window.ActiveXObject){
		// 枚举IE中XMLHttpResult对象的创建
		var msxmls = new Array(
			'Msxml12.XMLHTTP.5.0',
			'Msxml12.XMLHTTP.4.0',
			'Msxml12.XMLHTTP.3.0',
			'Msxml12.XMLHTTP',
			'Microsoft.XMLHTTP'
		);
		for(var i = 0; i < msxmls.length; i++){
			try{
				return new ActiveXObject(msxmls[i]);
			}catch(e){
			}
		}
	}
	// 无法创建将抛出异常
	throw new Error("不能创建XMLHttpRequest对象!");
}


2、封装异步请求对象
Asynchronous.js的封装代码如下:
// 定义Asynchronous对象
function Asynchronous(){
	// 定义Asynchronous对象的_xmlhttp属性并初始化为一个XMLHttpRequest对象
	this._xmlhttp = new FactoryXMLHttpRequest();
}

function Asynchronous_call(url){
	// 此变量在匿名内部类中使用,由javascript管理,对象呗回收的时候此变量才会被回收
	var instance = this; 
	// 第三个参数为true,表示使用异步请求的方式
	this._xmlhttp.open('GET',url,true);
	this._xmlhttp.onreadystatechange = function(){
		switch(instance._xmlhttp.readyState){
		case 1: // 请求正在被处理,结果不应该被处理
			instance.loading();
			break;
		case 2: // 请求已经加载了结果数据,正在对数据进行访问钱的准备
			instance.loaded();
			break;
		case 3: // 脚本可以与XMLHttpRequest对象进行交互,然而数据尚未完全加载完成
			instance.interactive();
			break;
		case 4: // 请求和结果都已经加载完成,并且加载为一个对象模型
			instance.complete(instance._xmlhttp.status,
				instance._xmlhttp.statusText,
				instance._xmlhttp.responseTest,
				instance._xmlhttp.responseXML);
			break;
		}
	};
	this._xmlhttp.send(null);
}

function Asynchronous_loading(){}
function Asynchronous_loaded(){}
function Asynchronous_interactive(){}
function Asynchronous_complete(status, statusText, responseText, responseXML){}

Asynchronous.prototype.loading = Asynchronous_loading;
Asynchronous.prototype.loaded = Asynchronous_loaded;
Asynchronous.prototype.interactive = Asynchronous_interactive;
Asynchronous.prototype.complete = Asynchronous_complete;

Asynchronous.prototype.call = Asynchronous_call;

    为了用javascript声明一个类,你需要声明一个具有这个类名的函数。声明的函数叫做一个构造器。在类Asynchronous的情况下,需要声明一个标识为Asynchronous的函数。当一个类使用new关键字实例化时,对象是空的,简单的说就是没有方法和属性。
    可以使用prototype属性来定义默认的属性和方法。当使用prototype属性进行定义时,每个定义的方法和属性在所有这种类型的实例之间共享。对于上面的Asynchronous类来说,有四个共享的方法:loading,loaded,interactive,complete,任何时候异步请求更新它的状态时都会调用。在默认情况下,所有方法不做任何事情,仅仅是一个占位符,这样不会发生任何异常。如果没有使用prototype属性,在构造器中分配方法,每个实例将拥有自己的一份函数副本。
对以上实现的一个用法如下(客户端):
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	
	<script language="javascript" src="js/factory.js"></script>
	<script language="javascript" src="js/asynchronous.js"></script>
	
	<script language="javascript" type="text/javascript">
		function asyncUpdateEvent(status, statusText, responseText, responseXML){
			// alert(1);
			document.getElementById('httpcode').innerHTML = status;
			document.getElementById('httpstatus').innerHTML = statusText;
			document.getElementById('result').innerHTML = responseText;
			document.getEl