httpclient.js

来自「Ajax基础入门小例子,运用Javascript+XMLHttpRequest对」· JavaScript 代码 · 共 82 行

JS
82
字号
function HttpClient(){}
HttpClient.prototype={
	//传给open方法的GET,POST类型
	requestType:'GET',
	//当设置为true时,将发出异步调用
	isAsync:false,
	//保存XMLHttpRequest实例的地方
	xmlhttp:false,
	//当发送一个成功的异步调用后将调用的内容
	callback:false,
	//当调用XMLHttpRequst的send方法时将调用的内容
	//为onSend设置自定义的函数,使其能够自定义载入的效果
	onSend:function(){
		document.getElementById('HttpClientStatus').style.display='block';
		},
	//该调用将在回调函数之前进行
	onLoad:function(){
		document.getElementById('HttpClientStatus').style.display='none';
		},
	onError:function(error){
		alert(error);
		},
	//实例化一个xmlhttpclient的方法
	init:function(){
		try{
			//Mozilla.safri
			this.xmlhttp=new XMLHttpRequest();
			}catch(e){
				//IE
				var XMLHTTP_IDS=new Array('MSXML2.XMLHTTP.5.0',
										   'MSXML2.XMLHTTP.4.0',
										   'MSXML2.XMLHTTP.3.0',
										   'MSXML2.XMLHTTP',
										   'Microsoft.XMLHTTP');
				var success=false;
				for(var i=0;i<XMLHTTP_IDS.length&&!success;i++){
					try{
						this.xmlhttp=new ActiveXObject(XMLHTTP_IDS[i]);
						success=true;
						}catch(e){}
					}
				if(!success){
					this.onError('Unable to create XMLHttpRequest.');
					}
				}
		},
	//发起页面请求的方法
	//@参数url,字符串型,请求的页面
	//@参数payload,字符串型,如果是POST请求就需要
	//发送该参数
	makeRequest:function(url,payload){
		if(!this.xmlhttp){
			this.init();
			}
		this.xmlhttp.open(this.requestType,url,this.isAsync);
		var self=this;
		//设置回调函数
		this.xmlhttp.onreadystatechange=function(){
			self._readyStateChangeCallback();
			}
			this.xmlhttp.send(payload);
			if(!this.isAsync){
				return this.xmlhttp.responseText;
				}
		},
	
	_readyStateChangeCallback:function(){
		switch(this.xmlhttp.readyState){
			case 2:
				this.onSend();
				break;
			case 4:
				this.onLoad();
				if(this.xmlhttp.status==200){
					this.callback(this.xmlhttp.responseText);
					}else{
						this.onError('HTTP Error Making Request:'+'['+this.xmlhttp.status+']'+this.xmlhttp.statusText);
						}
						break;
			}
		}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?