为了方便大家阅读,直接截图上传,后面附有代码,可以复制粘贴:

// 参数情况
// 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);
}
}
}
}
网友评论