小白学AJAX-04-ES6代码

ajax-es6

function ajax (options) {
function setOptions (options) {
const fn = () => {}
const defaultOpts = {
method: 'get',
url: '',
async: true,
param: '',
data: null,
success: fn,
error: fn
}
const opts = Object.assign(defaultOpts, options)
opts.method = opts.method.toUpperCase()
return opts
}
function createXHR () {
return (window.XMLHttpRequest || window.ActiveXObject)('Microsoft.XMLHTTP')
}
function paramStringify (param) {
const arr = []
for (let key in param) {
arr.push(`${key}=${param[key]}`)
}
return arr.join('&')
}
function bindChange (xhr, opts) {
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
const status = xhr.status
if ((status >= 200 && status < 300) || status === 304) {
const res = JSON.parse(xhr.responseText)
opts.success && opts.success(res)
} else {
opts.error && opts.error(xhr)
}
}
}
}
function setGet (opts) {
if (/get/i.test(opts.method)) {
const paramStr = paramStringify(opts.param)
const connect = opts.url.indexOf('?') > -1 ? '&' : '?'
opts.url += opts.connet + paramStr
}
}
function setPost (xhr, opts) {
if (/post/i.test(opts.method)) {
xhr.setRequestHeaders('Content-type', 'application/x-www-from-urlencoded')
if (opts.data) {
opts.data = paramStringify(opts.data)
}
}
}
function init() {
const xhr = new createXHR()
const opts = setOptions(options)
setGet(opts)
xhr.open(opts.method, opts.url, opts.async)
xhr.setPost(xhr, opts)
xhr.send()
}
init()
}

 

结尾

1. 可以用qs.js库取代paramStringify;

2. 还可以尝试加入timeout参数、abort方法、promise方式、Interceptor拦截器...;

3. 通过ajax可以延展很多其它知识点;

4. 文中的代码如有不足之处,请大家多多指点。

posted @ 2018-07-24 08:14  hefunc  阅读(216)  评论(0)    收藏  举报