為了方便大家閱讀,直接截圖上傳,后面附有代碼,可以復制粘貼:
// 參數情況
// method,url,data
function ajax(method, url, data, callback) {
// 1、創建請求對象
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
// 2、配置請求參數并發送請求
method = method.toUpperCase();
if (method == 'GET') {
xhr.open('GET', url + '?' + data, true);
xhr.send(null);
} else if (method == 'POST') {
xhr.open('POST', url, true);
xhr.send(data);
} else {
console.error('請傳入合法的請求方式');
}
// 3、監聽狀態
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 向外返回服務器的數據
// 根據responseXML屬性的是是否為空推斷出數據格式
// xhr.resopnseXML為null,表示請求的是json數據,否則,請求的是xml數據
if (!xhr.responseXML) {
callback(xhr.responseText);
} else {
callback(xhr.responseXML);
}
}
}
}