封装Ajax
原理:
1、浏览器
2、ajax
对象
3、ajax.open(method,url,true);
发送请求
4、ajax.send();
5、onreadystatechage
监听事件
6、status == 200 403 503
//封装兼容函数,Ajax函数 ajaxFunc(method, url , data, callback, flag)
function ajaxFunc(method, url, data, callback, flag) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
method = method.toUpperCase();
if (method == 'GET') {
xhr.open(method, url + '?' + data, flag);
xhr.send();
} else {
xhr.open(method, url, flag);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(xhr.responseText);
}
}
}
}