+ function () {
//---------------默认值
var defaults = {
url: '',
method: 'get',
async: true,
data: null,
dataType: 'json',
cache: true,
timeout: null,
headers: null,
success: null,
error: null
}
function ajax(options) {
return new init(options)
}
ajax.prototype = {
constructor: ajax,
send: function send() {
//---------------对象解构
var {
url,
method,
async,
data,
dataType,
timeout,
cache,
success,
error,
headers
} = this.options;
var xhr = this.xhr= new XMLHttpRequest;
//------------------------处理data
data = this.handleData();
var reg = /^(get|delete|head|options)$/i;
if (data && reg.test(method)) {
url += `${this.hasQuestion(url)}${data}`;
data = null;
}
//---------------------处理缓存-->cache
if (reg.test(method) && !cache) {
var time = new Date().getTime();
url += `${this.hasQuestion(url)}-=${time}`;
}
//----------------------处理timeout
if (timeout) xhr.timeout = timeout;
xhr.open(method, url, async);
//----------------处理请求头headers
if (headers && toString.call(headers) == "[object Object]") {
for (var key in headers) {
if (!headers.hasOwnProperty(key)) break;
xhr.setRequestHeader(key, encodeURI(headers[key]))
}
}
xhr.onreadystatechange = () => {
var str = "";
if (xhr.readyState === 4) {
if (/^(2|3)\d{2}$/.test(xhr.status)) {
switch (dataType.toUpperCase()) {
case 'JSON':
str = JSON.parse(xhr.response)
break;
case 'TEXT':
str = xhr.responseText;
break;
case 'XML':
str = xhr.responseXML;
break;
}
success && success(str, xhr.statusText, xhr)
} else {
error && error(xhr.response, xhr.statusText, xhr)
}
}
}
xhr.send(data)
},
hasQuestion: function hasQuestion(url) {
return url.includes('?') ? "&" : "?";
},
//---------------对象转字符串
handleData: function handleData() {
var data = this.options.data;
if (data == undefined || typeof data === "string") return data;
var res = "";
for (var key in data) {
if (!data.hasOwnProperty(key)) break;
res += `${key}=${data[key]}&`
}
return res.slice(0, res.length - 1)
}
}
function init(options) {
this.options = Object.assign({}, defaults, options);
if (!options.url) throw new Error('url must be a area');
this.send()
}
init.prototype = ajax.prototype;
window.ajax = window._ = ajax
}()
_({
url: 'data.json',
method: 'get',
async: true,
cache: false,
data: {
sex: 'men',
job: 'web'
},
headers: {
name: 11,
age: 22
},
success: (data, statusText, xhr) => {
console.log(data, statusText, xhr);
},
error: (data, statusText, xhr) => {
console.log(data, statusText, xhr);
}
})
JQ版AJAX源码简单处理
最新推荐文章于 2023-11-18 15:14:48 发布