原生ajax简单封装步骤:
var xhr =null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open(“方式”,”地址”,”标志位”);
xhr.setRequestHeader(“”,””);
xhr.send();
xhr.onreadystatechange =function(){}
原生ajax详细封装代码
function ajax(data) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var type = data.method === 'get' ? 'get' : 'post';
var url = '';
if (data.url) {
url = data.url;
if (type === 'post') {
url += "?" + data.params + "&_t=" + new Date().getTime();
}
}
var flag = data.async === 'true' ? 'true' : 'false';
xhr.open(type, url, flag);
if (type === 'get') {
xhr.send(null);
} else if (type === 'post') {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data.params);
}
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
if (typeof data.success === 'function') {
var d = data.dataType === 'xml' ? xhr.responseXML : xhr.responseText;
data.success(d);
}
} else {
if (typeof data.failure === 'function') {
data.failure();
}
}
}
}
}
window.onload = function () {
var btn = document.getElementById('btn');
btn.onclick = function () {
var param = {
url: '',
method: 'post',
async: true,
dataType: 'json',
params: {name: 'xiaoke', password: '110'},
success: function (data) {
alert(data);
},
failure: function () {
alert("亲,服务器请求超时!")
}
};
ajax(param);
}
}