AJAX超时处理

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<style type="text/css">
body,#colorup{
	font-family:Tahoma,"宋体";
	font-size:12px;
}
</style>
<script type="text/javascript" src="./ajax.js"></script>
<script type="text/javascript">
function $(s){
	return document.getElementById(s);
}

function jsonDecode(s){
	return (new Function("return " + s))();
}

function test1(){
	 (new Ajax()).get("./process.php?test=1",'',$("view"),"test1正在读取数据……"); // 这里可以传入一个loading的图片地址
}

function test2(){
	(new Ajax(function(){
		$("view").innerHTML = "test2正在读取数据,请稍候";
	},function(s){
		$("view").innerHTML = s;
	},function(){
		$("view").innerHTML = "Sorry,请求超时!";
	},5000) ).send("./process.php?test=2",{author:"fyland",mail:"ichenshy@gmail.com",date:"2010-06-03"},"POST");
}

function test3(){
	var jx = new Ajax();
	jx.before = function(){
		$("view").innerHTML = "test3正在读取数据,请稍候";
	}

	jx.after = function(s){
		var r = jsonDecode(s);
		for ( var k in r ){
			alert(k + ' : ' + r[k]);
		}
		$("view").innerHTML = "test3数据读取完毕";
	}

	jx.timeout = function(){
		$("view").innerHTML = "Sorry,TEST3请求超时!";
	}

	jx.time = 5000;

	var data = {
					author: "fyland",
					mail  : "ichenshy@gmail.com",
					date  : "2010-06-03"
				};

	jx.send("./process.php?test=3",data,"GET");
}
</script>
</head>
<body>
<div id="view"></div>
<div>
	<input type="button" onclick="test1();" value=" TEST1 " />

	<input type="button" onclick="test2();" value=" TEST2 " />

	<input type="button" onclick="test3();" value=" TEST3 " />
</div>
</body>
</html>

 

/*!
* 一个简单的Ajax类
* author: ichenshy@gmail.com
* date:   2010/06/04 Friday
*
* @param function fnBefore     用户自定义函数 Ajax开始前执行,若无则为null
* @param function fnAfter      用户自定义函数 Ajax完成后执行,若无则为null
* @param function fnTimeout    用户自定义函数 Ajax请求超时后执行,若无则为null
* @param integer  iTime        设置超时时间 单位毫秒
* @param boolean  bSync        是否为同步请求,默认为false
*/

function Ajax(fnBefore,fnAfter,fnTimeout,iTime,bSync){
	this.before		= fnBefore;
	this.after		= fnAfter;
	this.timeout	= fnTimeout;
	this.time		= iTime ? iTime : 10000;
	this.async		= bSync ? false : true;
	this._request	= null;
	this._response	= null;
}

Ajax.prototype = {
	/**
	*  将需要发送的数据进行编码
	*
	*  @param object data  JSON格式的数据,如: {username:"fyland",password:"ichenshy"}
	*/
	formatParam : function( data ){
		if ( ! data || typeof data != "object" ) return data;
		var k,r = [];
		for ( k in data ) {
			r.push([k,'=',encodeURIComponent(data[k])].join(''));
		}
		return r.join('&');
	},

	/**
	* 创建 XMLHttpRequest对象
	*/
	create : function(){
		if( window.XMLHttpRequest ) {
			this._request = new XMLHttpRequest();
		} else {
			try {
				this._request = new window.ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
		}
	},

	/**
	* 发送请求
	*
	* @param string				url     请求地址
	* @param object or string   data    可以是字符串或JSON格式的数据,如: {username:"fyland",password:"ichenshy"}
	* @param string             method  请求方式 : GET or POST
	* @param boolean            ifCache	返回数据是否在浏览器端缓存,默认为false;
	*/
	send : function(url,data,method,ifCache){
		if ( typeof this.before == "function" ) this.before();

		method = method.toUpperCase();
		this.create();

		var self = this;
		var timer = setTimeout(function(){
				if ( typeof self.timeout == "function" ) self.timeout();
				if ( self._request ) {
					self._request.abort();
					self._request = null;
				}
				return true;
			},this.time);

		var sendBody  = this.formatParam(data);

		if ( 'GET' == method ) {
			url = [url, ( url.indexOf('?') == -1 ? '?' : '&') ,sendBody].join('');
			sendBody = null;
		}

		if ( ! ifCache ) {
			url = [url, ( url.indexOf('?') == -1 ? '?' : '&') , "ajaxtimestamp=" , (new Date()).getTime()].join('');
		}

		this._request.open(method,url,this.async);
		if ( "POST" == method ) this._request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

		this._request.onreadystatechange = function(){
			if( self._request.readyState==4 ){
				if ( self._request.status==200 ){
					if ( timer ) clearTimeout(timer);
					self._response = self._request.responseText;
					if ( typeof self.after == "function") self.after(self._response);
				}
			}
		}
		this._request.send( sendBody );
	},

	/**
	*   简单的GET请求
	*
	*   @param string url  请求地址
	*   @param null or string or object	data
	*   @param object html element or string id	  e
	*   @param string loading                     loading时在e中的显示
	*   @param boolean  ifCache    浏览器是否缓存
	*/
	get : function(url,data,e,loading,ifCache){
			if ( typeof e == "string" ) e = document.getElementById(e);
			if ( loading ) {
				var rg = /\.(gif|jpg|jpeg|png|bmp)$/i;
				if ( rg.test(loading) ){
					loading = ['<img src="', loading , '"  align="absmiddle" />'].join('');
				}
				this.before = function(){e.innerHTML = loading;}
			}
			this.after		= function(s){e.innerHTML = s;}
			this.timeout	= function(){e.innerHTML = ' 请求超时! ';}
			this.send(url,data,"GET",ifCache ? true : false);
	}
};

 ajax超时处理重点关注红色部分,包括jquery、Prototype处理都一样,如下例:

request: function(){//AJAX请求
		//获得传输数据
		var data = this.getData();
		//2,ajax请求
		var self = this;
		var timer = setTimeout(function(){
			alert("超时咯");
		},5000);
		new Ajax.Request(
				this.url,{
				method :'post',
				encoding : 'GBK',
				parameters : data,
				onLoading  : this.onLoading(),
				onComplete : function(t){self.callBack(t);},
				on404 : this.on404
				
			}
		);
	}

 

 如果是调用成功,则需要去掉超时,如下:

request: function(){//AJAX请求
		//获得传输数据
		var data = this.getData();
		//2,ajax请求
		var self = this;
		
		var timer = setTimeout(function(){
			alert("超时啦!!")
		},5000);
		
		new Ajax.Request(
				this.url,{
				method :'post',
				encoding : 'GBK',
				parameters : data,
				onLoading  : this.onLoading(),
				onComplete : function(t){
					if( t.readyState==4 ){
						if ( t.status==200 ){
							if ( timer ) clearTimeout(timer);
						}
					}
					self.callBack(t);},
				on404 : this.on404
			}
		);
	}

 

展开阅读全文

没有更多推荐了,返回首页