封裝自己的Ajax函數
主要是兼容自己的get,post兩種不同請求的請求方式,在實現一下兼容的處理
ajax.open(method,url,true) 方法post get 請求地址 異步true 同步false
ajax.send() 發送
onreadystatechange 監聽數據 返回4 數據已經請求回來了
代碼實現:
function ajaxFn(method, url, callBack,data,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 if (method == 'POST') {
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) {
// xhr.responseText //返回回來的值
callBack(xhr.responseText);
}
}
}
}
