在对ajax进行封装前,我们先定义好传入数据的格式为一个对象,在此我们假设传入对象名为json
传入json的格式如下:
json = {
type : 'get' ,//数据传输的方式
url : 'url地址',//数据传输的地址
async : 'true',//是否异步
date : {
//需要传输的数据
},
success : function(){
//成功后执行的回调函数
},
error: function(){
//失败后执行的回调函数
}
}
在进入函数时首先要判断是否有数据传入,如果没有,直接返回不执行
if(!json){
return
}
如果有数据传入,我们也要对数据进行初始化,防止有些数据没有传入造成数据的值为undefined
json.type = json.type.toUpperCase() || 'GET';
json.url = json.url || '';
json.async = json.async || trur;
json.data = json.data || null;
json.success = json.success || function(){};
json.error = json.error || function(){};
由于传输的数据是以对象传进来的,而在ajax传输的时候传输的数据是以键值对形式传递,键与值之间用‘=’连接,键值对之间以‘&’连接,所以我们要对传入的数据进行处理,将传入的对象转为ajax需要的字符串类型
let arr = [];
for(let key in json.data){
arr.push(key + '=' + json.data[key]);
}
let str = arr.join('&');
到此前期的数据处理就结束了,接下来就可以进行ajax的相关操作
首先,创建XMLHttpRequest对象,
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
判断传输数据方式,通过这个对象的open方法与服务器建立连接,并将请求用send方法发送给服务器
if(json.type === 'GET'){
xhr.open(json.type,json.url + '?' + str,json.async);
xhr.send(null);
}else if(json.type === 'POST'){
xhr.open(json.type,json.url,json.async);
xhr.setRequestHeader('Content-type','Application/x-www-form-urlcoded;charset=uth-8');
xhr.send(str);
}
最后,通过事件监听请求状态与状态码,判断状态码,执行对应的回调函数
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
if(json.success instanceof Function){
json.success(xhr.responseText);
}
}else{
if(json.error instanceof Function){
json.error();
}
}
}
}
readyState 为请求状态
0 : 请求初始化(还没调用open())
1 : 请求已建立,但还没有发送(还没调用send())
2 : 请求已发送,正在处理中
3 : 请求在处理中
4 : 响应已完成
status 为服务器响应的状态码,
1开头表示请求继续
2开头表示成功,常见的有
200 标准请求成功
201 创建成功
203 服务器已成功处理请求,但返回信息可能来自另一源
204 服务器已成功处理请求,但是没有任何数据返回
3开头也表示成功,一般表示重定向
4开头表示发生错误
400 请求的语法服务端不认识
401 未授权
403 服务器拒绝了你的请求
404 服务器找不到你请求的url
407 你的代理没有授权
408 请求超时
410 你请求的数据已被服务端永久删除
5开头表示服务端出现错误
好了,完整代码来了!!!
function $ajax(json){
if(!json){
return;
}
json.type = json.type.toUpperCase() || 'GET';
json.url = json.url || '';
json.async = json.async || true;
json.data = json.data || null;
json.success = json.success || function(){};
json.error = json.error || function(){};
let arr = [];
for(let key in json.data){
arr.push(key + '=' + json.data[key]);
}
let str = arr.join('&');
let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
if(json.type === 'GET'){
xhr.open(json.type,json.url + '?' + str,json.async);
xhr.send(null);
}else if(json.type === 'post'){
xhr.open(json.type,json.url,json.async);
xhr.setRequestHeader('Content-type','Application/x-www-form-urlcoded;charset=uth-8');
xhr.send(str);
}
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
if(json.success instanceof Function){
json.success(xhr.responseText);
}
}else{
if(json.error instanceof Function){
json.error();
}
}
}
}
}