提供對原生ajax的簡易封裝
/*
* 封裝ajax庫
* author: wenqian
* email: 843462167@qq.com
*/
(function() {
/*
* 創建 XMLHttpRequest 對象的語法
* XMLHttpRequest IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
* ActiveXObject IE6, IE5 瀏覽器執行代碼
*/
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject("Microsoft.XMLHTTP")
// 配置
var config = {
url: '',
method: 'get',
headers: {
'Content-Type': 'application/json'
},
// 提供path query選項
getParamsWhere: 'query'
}
/*
* 發送請求
* url 請求地址
* method 請求方式
* params 參數
* headers 頭部信息
*/
var send = (method = config.method, url, params, headers = config.headers) => {
console.log(headers)
// 設置header
return new Promise((resolve, reject) => {
// url不存在時候
if (!url) return reject(response('url錯誤', 'error'))
try {
xhr.open(method, url, true)
if (headers && typeof headers === 'object') {
for (var head in headers) xhr.setRequestHeader(head, headers[head])
}
xhr.send(params ? JSON.stringify(params) : '')
xhr.onerror = (error) => {
return reject(response(error, 'error'), xhr.status)
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
return reject(response(JSON.parse(xhr.responseText), 'success'), xhr.status)
}
}
} catch (e) {
return reject(response(e, 'error'))
}
})
}
/*
* params 必須爲對象 可傳可不傳參
* isQuery query 和path 參數
*/
var get = (url, params, headers, isQuery = config.getParamsWhere) => {
return send('GET', delUrl(url, params, isQuery), '', headers)
}
var post = (url, params, headers) => {
return send('POST', url, params, headers)
}
// 處理url 返回query傳參,或者path傳參
var delUrl = (url,params, isQuery) => {
// 處理url
var str = ''
if (typeof params === 'object') {
for (var i in params) {
str += `${i}=${params[i]}&`
}
} else {
str = ''
}
str = str.substr(0, str.length - 1)
isQuery === 'query' ? str = `?${str}` : isQuery === 'path'? str = `/${str.replace(/&|=/g, '/')}` : str = ''
url = url + str
return url
}
// 處理返回數據
var response = (data, status = 'success', code = '200') => {
return typeof data === 'string' ? { message: data, status: status, code: code } :
{ data: data, status: status, code: code }
}
// 調用
get('http://127.0.0.1/shop/public/index.php/index/Books/getBooks', { createtime: '2017-11' }).then(res => {
console.log(res)
}).catch(res => {
console.log(res)
})
})()