
原生ajax封装,包含post、method方式
function ajax(method, url, data, success) {
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//get时,且数据存在,URL需要用?连接
if (method == 'get' && data) {
url += '?' + data;
} xhr.open(method,url,true);
if (method == 'get') {
xhr.send();//get,发送时空的
} else {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');//设置请求头
xhr.send(data);//发送里,放数据
} xhr.onreadystatechange = function() { if ( xhr.readyState == 4 ) {
if ( xhr.status == 200 ) {
success && success(xhr.responseText);
} else {
alert('出错了,Err:' + xhr.status);
}
} }
}