原生ajax类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原生ajax类相关的知识,希望对你有一定的参考价值。
- 代码:
/* @desc ajax请求类 @author lee [<[email protected]>] @param data object { data # 发送到后台的数据,支持json和表单 url # 请求的接口地址 type # 请求方式 get或post async # 同步或异步 true:异步 false:同步 json # 发送的数据是否是json还是表单 true:json false:表单 auth # 后台授权验证 默认为空 } */ function ajax(){ this.xhr this.data this.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类的主要内容,如果未能解决你的问题,请参考以下文章