代码以下ajax
class AJAX {
constructor({url = "",method = "GET",data = {},async = true,success,error,resType = "",headers = {}},time = 5000) {
//集中管理传递过来的参数
this.option = {url,method,data,async,success,error,resType,headers,time};
this.timeout;
this.xhr = new XMLHttpRequest();
this.start();
}
start() {
//数据校验
this.checkOption();
//数据格式的统一
this.initOption();
//创建链接
this.open();
//设置请求头
this.setHeaders();
//设置返回数据格式
this.setResponseType();
//发送数据
this.sendData()
//返回成功或失败
this.responseData();
};
}
复制代码
代码以下json
checkOption() {
let {url,async,resType,headers,time} = this.option;
if (url === '') {
throw new Error('请求地址不能为空'); //打印错误信息,并中止当前进程
//Console.error('请求地址为空'); 也能够打印错误信息,可是不能中止当前进程
}
if(typeof headers !== 'object'){
throw new Error('设置请求头时请传入 {key:value,key:value...} 的格式');
}
if(typeof resType !== 'string'){
throw new Error('设置返回数据格式时请传入字符出串格式');
}
if(typeof time !== 'number'){
throw new Error('超时时间请传入数字类型数据');
}
if (typeof url !== 'string') {
//输出警告信息
console.warn('当前请求地址不是字符串,如今将其尝试转换为字符串');
}
if (async === false && resType != '') {
console.warn('若是设置了请求方式为同步,即便设置了返回数据格式也不会生效');
}
};
复制代码
须要注意的是返回数据格式能够设置这几个值,以后会写一个详细的传参指南api
initOption() {
let {url,async,method} = this.option;
//url不是字符串转换成字符串
if (typeof url !== 'string') {
try {
this.option.url = url.toString();
console.log(`转换成功: "${this.option.url}"`);
} catch (error) {
throw new Error('url 转换字符串失败');
}
}
//async不是布尔型转成布尔型
if(typeof async !=='boolean'){
async == true ? this.option.async = true : this.option.async = false;
}
//将 post get 转换为大写
this.option.method = method.toUpperCase();
//post和get数据初始化
if(this.option.method != 'FORMDATA'){// [1]
let data = this.option.data;
if(typeof data === 'object'){//[2]
if( this.option.method === 'GET'){
let arr=[];
for(let name in data){
arr.push(`${name}=${data[name]}`);//[3]
}
let strData=arr.join('&');//[4]
this.option.data=`?${strData}`;//[5]
}else if( this.option.method === 'POST'){
let formData = new FormData();//[6]
for(let key in data){
formData.append(`${key}`,`${data[key]}`);
}
this.option.data=formData;
}
}else if(typeof data === 'string' && this.option.method === 'GET'){//[7]
this.option.data=`?${data}`;
}
}
};
复制代码
通过以前的数据处理这里只须要判断下是 GET 仍是其余方式(post formdata),而后选择对应的链接方式promise
open(){
let {method,url,async,data} = this.option;
if(method === 'GET'){
this.xhr.open(method,url+data,async);
}else{
this.xhr.open(method,url,async);
}
}
复制代码
将传入的参数进行解析,而后设置自定义请求头 代码以下bash
setHeaders(){
let headers = this.option.headers;
for(let key in headers){
this.xhr.setRequestHeader(`${key.toString()}`,`${headers[key].toString()}`)
}
}
复制代码
setResponseType() {
if (this.option.async) {
this.xhr.responseType = this.option.resType;
}
}
复制代码
sendData(){
if(this.option.method == 'GET'){
this.xhr.send();
}else{
this.xhr.send(this.option.data);
}
this.timeout = setTimeout(()=>{
typeof this.option.error === 'function' && this.option.error('请求超时,默认超时时间为 5000 毫秒');
this.option.reject('请求超时,默认超时时间为 5000 毫秒');
}, this.option.time);
}
复制代码
responseData(){
this.xhr.onload = ()=>{
if(this.xhr.status >= 200 && this.xhr.status < 300 || this.xhr.status === 304){
typeof this.option.success === 'function' && this.option.success(this.xhr.response);
}else{
typeof this.option.error === 'function' && this.option.error(this.xhr.statusText);
}
}
}
复制代码
在实现基本功能后,忽然想到 jQuery 的 ajax 是会返回一个 promise 对象,能够同时使用回掉函数,或者使用 then 和 catch 来处理数据
所以修改了下传入参数,以及返回数据的处理cookie
传参时代码以下app
//add resolve reject
class AJAX {
constructor({url = "",method = "GET",data = {},async = true,success,error,resType = "",headers = {},resolve,reject}) {
this.option = {url,method,data,async,success,error,resType,headers,resolve,reject};
this.xhr = new XMLHttpRequest();
this.start();
}
}
复制代码
返回数据时代码以下异步
responseData(){
this.xhr.onload = ()=>{
if(this.xhr.status >= 200 && this.xhr.status < 300 || this.xhr.status === 304){
clearTimeout(this.timeout);
typeof this.option.success === 'function' && this.option.success(this.xhr.response);
this.option.resolve(this.xhr.response);//add
}else{
clearTimeout(this.timeout);
typeof this.option.error === 'function' && this.option.error(this.xhr.statusText);
this.option.reject(this.xhr.statusText);//add
}
}
}
复制代码
class AJAX {
constructor({url = "",method = "GET",data = {},async = true,success,error,resType = "",headers = {},resolve,reject}) {
this.option = {url,method,data,async,success,error,resType,headers,resolve,reject};
this.xhr = new XMLHttpRequest();
this.start();
}
start() {
//数据校验
this.checkOption();
//数据格式的统一
this.initOption();
//创建链接
this.open();
//设置请求头
this.setHeaders();
//设置返回数据格式
this.setResponseType();
//发送数据
this.sendData()
//返回成功或失败
this.responseData();
};
checkOption() {
let {url,async,resType,headers} = this.option;
if (url === '') {
throw new Error('请求地址不能为空'); //打印错误信息,并中止当前进程
//Console.error('请求地址为空'); 也能够打印错误信息,可是不能中止当前进程
}
if(typeof headers !== 'object'){
throw new Error('设置请求头时请传入 {key:value,key:value...} 的格式');
}
if(typeof time !== 'number'){
throw new Error('超时时间请传入数字类型数据');
}
if(typeof resType !== 'string'){
throw new Error('设置返回数据格式时请传入字符出串格式');
}
// "" 与设置为"text"相同, 是默认类型 (其实是 DOMString)
// "arraybuffer" 将接收到的数据类型视为一个包含二进制数据的 JavaScript ArrayBuffer
// "blob" 将接收到的数据类型视为一个包含二进制数据的 Blob 对象
// "document" 将接收到的数据类型视为一个 HTML Document 或 XML XMLDocument ,这取决于接收到的数据的 MIME 类型
// "json" 将接收到的数据类型视为 JSON 解析获得的
// "text" 将接收到的数据类型视为包含在 DOMString 对象中的文本
if (typeof url !== 'string') {
//输出警告信息
console.warn('当前请求地址不是字符串,如今将其尝试转换为字符串');
}
if (async === false && resType != '') {
console.warn('若是设置了请求方式为同步,即便设置了返回数据格式也不会生效');
}
};
initOption() {
let {url,async,method} = this.option;
//url不是字符串转换成字符串
if (typeof url !== 'string') {
try {
this.option.url = url.toString();
console.log(`转换成功: "${this.option.url}"`);
} catch (error) {
throw new Error('url 转换字符串失败');
}
}
//async不是布尔型转成布尔型
if(typeof async !=='boolean'){
async == true ? this.option.async = true : this.option.async = false;
}
//将 post get 转换为大写
this.option.method = method.toUpperCase();
//post和get数据初始化
if(this.option.method != 'FORMDATA'){
let data = this.option.data;
if(typeof data === 'object'){
if( this.option.method === 'GET'){
let arr=[];
for(let name in data){
arr.push(`${name}=${data[name]}`);
}
let strData=arr.join('&');
this.option.data=`?${strData}`;
}else if( this.option.method === 'POST'){
let formData = new FormData();
for(let key in data){
formData.append(`${key}`,`${data[key]}`);
}
this.option.data=formData;
}
}else if(typeof data === 'string' && this.option.method === 'GET'){
this.option.data=`?${data}`;
}
}
};
open(){
let {method,url,async,data} = this.option;
if(method === 'GET'){
this.xhr.open(method,url+data,async);
}else{
this.xhr.open(method,url,async);
}
}
setHeaders(){
let headers = this.option.headers;
for(let key in headers){
this.xhr.setRequestHeader(`${key.toString()}`,`${headers[key].toString()}`)
}
}
setResponseType() {
if (this.option.async) {
this.xhr.responseType = this.option.resType;
}
}
sendData(){
if(this.option.method == 'GET'){
this.xhr.send();
}else{
this.xhr.send(this.option.data);
}
this.timeout = setTimeout(()=>{
typeof this.option.error === 'function' && this.option.error('请求超时,默认超时时间为 5000 毫秒');
this.option.reject('请求超时,默认超时时间为 5000 毫秒');
}, this.option.time);
}
responseData(){
this.xhr.onload = ()=>{
if(this.xhr.status >= 200 && this.xhr.status < 300 || this.xhr.status === 304){
clearTimeout(this.timeout);
typeof this.option.success === 'function' && this.option.success(this.xhr.response);
this.option.resolve(this.xhr.response);//add
}else{
clearTimeout(this.timeout);
typeof this.option.error === 'function' && this.option.error(this.xhr.statusText);
this.option.reject(this.xhr.statusText);//add
}
}
}
all(promises) {
return Promise.all(promises);
};
}
function ajax({url,method,data,async,success,error,resType,headers,time}){
return new Promise((resolve, reject) => {
return new AJAX({url,method,data,async,success,error,resType,headers,time,resolve,reject});
});
}
复制代码
使用时能够将代码复制粘贴到单独的 js 文件而后用 script 标签引入
也能够添加一行 export 代码将最后的 ajax 暴露出去 使用import 引入async
具体使用方法用法函数
ajax({
url:'api/login',
method:'post',//支持 GET POST 和我自定义的 FORMDATA ,传入时不区分大小写
data = {
name:"yhtx",
id:"1997"
},//除了这种还支持字符串 "name=yhtx&id=1997";以及 formData 数据,在传入formData 数据时请将 method 设置为 FORMDATA
async = true,//能够使用数字 1 代替 true ,数字 0 代替 false
time = 5000,//请求超时时间,默认为 5000 毫秒
success(res){
//能够使用回调的形式处理数据也能够使用 then
},error(err){
//能够使用回调的形式处理错误也能够使用 catch
},
resType = "",//能够传入 "" "arraybuffer" "blob" "document" "json" "text"
headers = {
mycookie: "46afqwiocibQEIJfa498./&678" //使用对象的方式传参
}
}).then((res)=>{
//能够使用 then 的形式处理数据也能够使用回调函数
}).catch((err)=>{
//能够使用 catch 的形式处理数据也能够使用回调函数
})
复制代码