var $ = {

request:function(obj){

//1. 获得xmlhttprequest对象兼容性处理

var xhr; //undefined未定义

try{

//主流浏览器里面的ajax对象

xhr = new XMLHttpRequest();

}catch(e){

//IE低版本的浏览器

xhr = new ActiveXObject("Microsoft.XMLHTTP");

}

        //2. 建立和服务器的连接

      

if(obj.method=='get'){

xhr.open(obj.method,obj.url+'?'+obj.data+'&'+Math.random(),true);

xhr.send();

}else if(obj.method=='post'){

xhr.open(obj.method,obj.url,true);

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xhr.send(obj.data);

}

//监视服务器的处理状态

xhr.onreadystatechange = function(){

if(xhr.readyState==4 && xhr.status==200){

//说明请求成功了,输出服务器返回的数据

obj.callback(xhr.responseText);

}

}

}

}

欢迎关注,有问题一起学习欢迎留言、评论。

你要保守你心,胜过保守一切。

作者:刘俊涛的博客​