封装的ajax

function ajax(method,url,data,success){
if(window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
var xmlhttp = new XMLHttpRequest();
} else {
// IE6, IE5 浏览器执行代码
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(method =='get' && data){
url += '?' + data;
}
xmlhttp.open(method,url,true);
if(method =='get'){
xmlhttp.send();
}else{
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send(data);
}

xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
success && success(xmlhttp.responseText);
} else {

}
}

}
}

 

调用位置

ajax('post','demo.php',function(data){
alert(data);
}

posted @ 2017-01-05 23:06  不再犯错  阅读(158)  评论(0编辑  收藏  举报