當開發簡單頁面的時候,不需要引入任何js庫,這時需要封裝一個用到 XMLHttpRequest 對象的好用的接口請求。
simple 封裝如下
ajaxRequest({
url: '',
method: 'POST',
type: 'json',
data: {},
success: function(res) {
console.log(res)
},
erro: function(err) {
console.log(err)
}
})
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 后
var formData = [];
for(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.lenght > 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.responseType = option.type;
xhr.withCredentials = false; //指示是否應使用Cookie或授權標頭等憑據進行跨站點訪問控制請求。
// 5. 處理請求回調
xhr.onreadystatechange = 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, true); // 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);
}
