1.调用方式
ajax({
method: 'get',
url: 'http://host:port/pathname/xx',
async: true,
param: {
param1: 'value1',
param2: 'value2'
},
data: {
data1: 'value1',
data2: 'vaule2'
},
success: function () {},
error: function () {}
})
2.代码大纲
funciton ajax (optsion) {
// setOptions 处理参数
// paramStringify 参数字符串化
// createHHR 实例
// bindChange 监听响应
// setGet get处理
// setPost post处理,注意放xhr.opne()之后
// xhr.open()
// xhr.send()
}
3.设置参数
function setOptions (options) {
var opts = {
method: options.method || 'get',
url: options.url,
async: options.async !== false,
params: '',
data: '', success: null, error: null }
return opts }
4.参数字符串化
function paramStringify (param) {
const arr = []
for (let key in param) {
arr.push(key + '=' + param[key])
}
return arr.join('&')
}
5.实例XHR
function createXHR () {
return new (window.XMLHttpRequest || window.ActiveXObject)('Microsoft.XMLHTTP')
}
6.处理get
function setGet (xhr, opts) {
if (/get/i.test(opts.method) {
const paramStr = paramStringify(opts.param)
const connect = opts.url.indexOf('?') > -1 ? '&' : '?'
opts.url += connect + paramStr
}
}
7.处理post
function setPost (xhr, opts) {
if (/post/i.test(opts.method) {
xhr.setRequsetHeaders('Content-type', 'application/x-www-form-urlencoded')
if (opts.data) {
opts.data = paramStringify(opts.data)
}
}
}
8.监听响应
function bindChange (xhr, opts) {
xhr.onreadystatechange = function() {
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)
}
}
}
}
9. init函数
function init () {
const xhr = createXHR()
const opts = setOptions(options)
bindChange(xhr, opts)
setGet(opts)
xhr.open(opts.method,, opts.url, opts.async)
xhr.setPost(xhr, opts)
xhr.send(opts.data)
}