开发中有时要用到ajax,不可能每次都去ajax,因此就封装了ajax函数。该文不包括ajax的基础,若是有兴趣能够查看个人另一篇文章ajax的工做原理http://www.cnblogs.com/salmonlin/p/8962777.htmlhtml
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);
}
}
}
}ajax