ajax函数封装

开发中有时要用到ajax,不可能每次都去ajax,所以就封装了ajax函数。该文不包括ajax的基础,如果有兴趣可以查看我的另外一篇文章ajax的工作原理http://www.cnblogs.com/salmonlin/p/8962777.html

function ajax (method,url,data,success){  //四个参数,method是方法,url是路径,data是先后台传送的参数,success是后调函数
var xhr = null;
try{   //处理XMLHttpRequest对象的兼容性
xhr = new XMLHttpRequest();
}catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if(method == 'get' && data){
url += '?' + data;
}
xhr.open(method,url,true);
if(method == 'get'){
xhr.send();
}
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);
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/salmonlin/p/8962999.html
今日推荐