理解ajax技術,封裝原生 ajax請求
阿新 • • 發佈:2019-01-01
// 舉例1:jquery 的 ajax 請求如下
$.ajax({
url: 'http://118.31.238.237:8080/metro/get', //請求地址
type: 'GET', //請求方式
data: {cityId:2}, //請求引數
dataType: 'json',
success: (response) => {
console.log(response)
}
});
// 舉例2:封裝的 原生ajax 請求如下
function ajaxMy(options) {
let {
url,
type,
data,
dataType,
success,
fail,
} = options;
// 處理引數
type = type.toUpperCase();
dataType = dataType ? dataType : 'json';
let xhr = null ;
// 1. 建立 xhr 物件
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else { //IE6及其以下版本瀏覽器
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// 2. 初始化 並 傳送請求
if (type === 'GET') {
// 處理 get 方式的 請求引數
let requestParams = '?' ;
for (let [key, value] of Object.entries(data)) {
requestParams += `${key}=${value}&`;
}
requestParams = requestParams.slice(0, -1);
xhr.open('GET', url + requestParams);
xhr.send(null);
} else if (type === 'POST') {
// 將請求資料 放到 請求主體中,並沒有傳送
xhr.open("POST", options.url, true);
//設定表單提交時的內容型別
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 傳送請求
xhr.send(data);
}
// 3. 監聽
xhr.onreadystatechange = () => {
if (xhr.readyState ===4) {
if (xhr.status >= 200 && xhr.status < 300) {
success && success(JSON.parse(xhr.responseText));
} else {
fail && fail(xhr.status)
}
}
}
}
ajaxMy({
url: 'http://118.31.238.237:8080/metro/get',
type: 'GET',
data: {cityId:2},
dataType: 'json',
success: (response) => {
console.log(response)
}
});