现在的位置: 首页 > 综合 > 正文

js之自定义封装ajax类

2013年06月25日 ⁄ 综合 ⁄ 共 1421字 ⁄ 字号 评论关闭
//open("get",url),url要加Math.random()
	//send()发送请求,post的时候传入字符串参数,歧义值用encodeURIComponent
	//onreadystatechange readystate==4数据返回\status==200
	//responseText         responseXML得到一个xml对象,dom核心方法访问
	//setRequestHeader('content-Type','application/x-www-form-urlencoded')
	
	
	
	/*思路:
		1 兼容得到xhr对象
		2 是否get方式确定最后的url
		3 open方法调用
		4 注册onreadystatechange函数,根据readyState和status调用回调函数
		5 根据请求方式确定setRequestHeader是否调用和send的方法调用
	*/
	function Ajax(arg){
		/*
			arg:{
				url: 请求的url
				method:默认为get,不区分大小写
				success:function(response,xhr){
					//成功钩子函数
				},
				fail:function(response,xhr){        //reponse就是返回的文本
													//xhr就是XMLHttpRequest对象
					//失败钩子函数
				}
				params:{//传递的参数
					key:value
				}
			}
		*/
		this.arg = arg;
		var xhr = window.XMLHttpRequest ? 
					new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
		
		var data = this.encodeParam(this.arg.params);
		if(/^get$/i.test(this.arg.method)){
			this.arg.url += '?'+data+'&'+Math.random();//不缓存
		}else{
			this.arg.url +=  '?'+Math.random();
		}
		xhr.open(this.arg.method||'get',this.arg.url);
		xhr.onreadystatechange = function(){
			if(xhr.readyState==4&&xhr.status==200){
				this.arg.success(xhr.responseText,xhr);
			}
			if(xhr.readyState==4&&xhr.status!=200){
				this.arg.fail(xhr.responseText,xhr);
			}
		}
		if(/^post$/i.test(this.arg.method)){
			xhr.setRequestHeader('content-Type','application/x-www-form-urlencoded');
			xhr.send(data);
		}else{
			xhr.send();
		}
	}
	
	Ajax.prototype = {
		encodeParam:function(){//把传入的参数变成可传递的参数
			var ay = [];
			for(var i in this.arg.params){
				var r = encodeURIComponent(i)+'='+encodeURIComponent(this.arg.params[i]);
				ay.push(r);
			}
			return ay.join("&");
		}
	}

抱歉!评论已关闭.