1、封装函数
/**
* XMLHttpRequest 简单封装
* @param option
* @return {undefined}
*/
export function ajaxRequest (option) {
// 1. 首先简单验证传进来的参数是否合法
// if (Object.prototype.toString.call(option) !== '[object, Object]') return undefined
// 2. 对参数容错处理
option.method = option.method ? option.method.toUpperCase() : 'GET' // 默认 GET 请求
option.data = option.data || {}
option.type = option.type || 'json'
// 3. 如果是 GET 请求,需要处理 data 里的数据并且以一定的规则拼接到 url 后
if (option.method === 'GET') {
var formData = []
for (let key in option.data) { // Object.keys.forEach
formData.push(''.concat(key, '=', option.data[key]))
}
option.data = formData.join('&') // eg: a=b&c=d&e=f
if (option.method === 'GET' && formData.length > 0) { // 注意,option.data 为空对象的时候,就不用拼接参数了
// 连接本身有参数的时候拼接 &option.data,如果本身没有参数拼接 ?option.data
option.url += location.search.length === 0 ? ''.concat('?', option.data) : ''.concat('&', option.data)
}
}
// 4. 实例化 XMLHttpRequest 对象,并进行一些设置
var xhr = new XMLHttpRequest()
xhr.onload = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (option.success && typeof option.success === 'function') {
option.success(xhr.response)
}
} else {
if (option.error && typeof option.error === 'function') {
option.error(new Error(xhr.statusText))
}
}
}
}
xhr.open(option.method, option.url, option.async) // true 代表是异步请求
// 6. 如果是 POST 请求,需要设置请求头
if (option.method === 'POST') {
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
}
// 7. 发送请求
xhr.send(option.method === 'POST' ? option.data : null)
}
2、函数调用
import { ajaxRequest } from '@/utils/utils'
......
ajaxRequest(
{
url: url,
method: 'GET',
type: 'json',
data: {},
async: false,
success: function (res) {
let features = JSON.parse(res).features
if (features.length > 0) {
resinfo = features[0]
}
},
error: function () {
resinfo = null
}
})