Ajax请求GET/POST方法的封装

时间:2020-12-27 12:05:30

Ajax请求GET/POST方法的封装,网易微专业上的一道GET/POST方法封装练习题。

方法:get(url, options, callback) 参数

  1. url {String} 请求资源的url
  2. options {Object} 请求的查询参数
  3. callback {Function} 请求的回调函数,接收XMLHttpRequest对象的responseText属性作为参数 返回

举例: get(‘/information’, {name: ‘netease’, age: 18}, function (data) {console.log(data); });

描述:方法get(url, options, callback),是对Ajax请求GET方法的封装。下面是get方法的实现代码

function serialize(data){//对发送数据的序列化
if(!data) return '';
var pairs=[];
for(var name in data){
if(!data.hasOwnProperty(name)) continue;//排除嵌套对象
if(typeof data[name]==='function') continue;//排除操作数是函数
var value=data[name].toString();
//encodeURIComponent对同一资源表示符(URI)编码,
name=encodeURIComponent(name);
valeu=encodeURIComponent(value);
pairs.push(name+'='+value);
}
return pairs.join('&');
}
//get方法封装
function get(url,options,callback){
if(window.XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else if(window.ActiveXobject){//兼容IE7及以前版本
var xhr=new ActiveXobject('Microft.XMLHttp');
}
xhr.onreadystatechange=function(callback){
if(xhr.readyState==4){//请求结束时,readyState状态为4
if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
callback(xhr.responseText);
}else{
console.log('连接失败:'+xhr.status);
}
}
}
// http://localhost:8000/information?name=zhou&age=18
url=url+'?'+serialize(options);
xhr.open('get',url,true);//开启请求,readyState状态为1
xhr.send(null);//正式像服务器发送请求,readyState状态为2
}
//post方法封装
function post(url,options,callback){
if(window.XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else if(window.ActiveXobject){//兼容IE7及以前版本
var xhr=new ActiveXobject('Microft.XMLHttp');
}
xhr.onreadystatechange=function(callback){
if(xhr.readyState==4){//请求结束时,readyState状态为4
if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
callback(xhr.responseText);
}else{
console.log('POST请求连接失败:'+xhr.status);
}
}
}
xhr.open('post',url,true);//开启请求,readyState状态为1
xhr.send(serialize(options));//正式像服务器发送请求,readyState状态为2
}
post('/information',{name:'zhou',age:18},function(data){
console.log(data);
});
get('/information',{name:'zhou',age:18},function(data){
console.log(data);
});