/*@desc ajax请求类@author lee [<complet@163.com>]@param data object{data ???????# 发送到后台的数据,支持json和表单url ????????# 请求的接口地址type ???????# 请求方式 get或postasync ??????# 同步或异步 true:异步 false:同步json ???????# 发送的数据是否是json还是表单 true:json false:表单auth ???????# 后台授权验证 默认为空}*/function ajax(){this.xhrthis.datathis.init = function(){ ???if(window.XMLHttpRequest){ ???????this.xhr=new XMLHttpRequest() ???}else{ ???????this.xhr=new ActiveXObject("Microsoft.XMLHTTP") ???} ???return this}this.before = function(func){ ???this.xhr.addEventListener(‘readystatechange‘,function(){ ???????if(this.readyState < 4){ ???????????func() ???????} ???}) ???return this}this.success = function(func){ ???this.xhr.addEventListener(‘readystatechange‘,function(){ ???????if (this.readyState == 4 && this.status == 200){ ???????????var res ???????????if(this.getResponseHeader(‘content-type‘)===‘application/json‘){ ???????????????res = JSON.parse(this.responseText) ???????????}else{ ???????????????res = this.responseText ???????????} ???????????func(res) ???????} ???}) ???return this}this.error = function(func){ ???this.xhr.addEventListener(‘readystatechange‘,function(){ ???????if(this.readyState == 4 && this.status != 200){ ???????????func() ???????} ???}) ???return this}this.request = function(obj){ ???this.data = obj.data ???var url = obj.url ???var type = obj.type ???var async = obj.async ???var json = (obj.json===true)?true:false ???var auth = obj.auth ???this.init() ???this.xhr.open(type,url,async) ???if(json){ ???????this.xhr.setRequestHeader("Content-type", "application/json") ???????this.data = JSON.stringify(this.data) ???}else{ ???????this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded") ???} ???if(auth){ ???????this.xhr.withCredentials = true ???????this.xhr.setRequestHeader("Authorization", "Basic " + btoa(auth)) ???} ???return this}this.send = function(){ ???this.xhr.send(this.data)}}
var xhr = new ajax()var data = {data:‘name=lee‘,url:‘http://localhost/test.php‘,type:‘post‘,async:true,json:false}xhr.request(data).before(function(){console.log(1)}).success(function(data){console.log(data)}).error(function(){console.log(2)}).send()
原生ajax类
原文地址:http://blog.51cto.com/12173069/2109281