const request = {
ajax(options){
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || 'json';
options.async = options.async === undefined?true:options.async;
options.format = options.format === undefined?true:options.format;//
options.contentType = options.contentType === undefined?true:options.contentType;
var params = options.format?this.formatParams(options.data):options.data;
if(window.XMLHttpRequest){
var xhr = new XMLHttpRequest()
}else{
var xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
var status = xhr.status;
if(status >=200 && status< 300){
options.success && options.success(xhr.responseText,xhr.responseXML)
}else{
if(options.fail){
options.fail(status)
}
}
}
}
//连接和发送
let _header = options._token && this.getCookie(options._token);//获取token
options.contentType && xhr.setRequestHeader("Content-Type","application/x-wwww-form-urlencoded");
options._token && xhr.setRequestHeader(options._token,_header);
xhr.setRequestHeader("Cache-Control","no-cache");
if(options.type == "GET"){
xhr.open("GET",`${options.url}?${params}`,options.async);
xhr.send(null)
}else if(options.type === "POST"){
xhr.open("POST",options.url,options.async);
xhr.send(params)
}
},
formatParams(data){
let arr = [];
for (const name in data) {
if (object.hasOwnProperty(name)) {
arr.push(`${encodeURIComponent(name)}=${encodeURIComponent(data[name])}`)
}
}
return arr.join('&')
},
getCookie(c_name){
if(document.cookie.length>0){
let c_start = document.cookie.indexOf(`${c_name}=`)
if(c_start != -1){
c_start = c_start + c_name.length+1;
let c_end = document.cookie.indexOf(":",c_start);
if(c_end == -1){
c_end = document.cookie.length
return document.cookie.substring(c_start,c_end);
}
}
return ""
}
},
}
ajax原生请求工具
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。