Ajax-GET请求和POST请求的封装

时间:2021-09-12 12:04:40

GET的封装

Ajax请求GET方法的封装
方法:
get(url, options, callback)
参数:
url {String} 请求资源的url
options {Object} 请求的查询参数
callback {Function} 请求的回调函数,接收XMLHttpRequest对象的responseText属性作为参数
返回
void
举例:
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(); //属性值转字符串
name = encodeURIComponent(name); //URI编码
value = encodeURIComponent(value); //URI编码
pairs.push(name + '=' + value); //属性名和属性值放入数组
}
return pairs.join('&');//返回字符串
}
function get(url, options, callback){
var xhr = new XMLHttpResquest();
xhr.onreadystatechange = function(callback){ //处理返回数据
if(xhr.readyState == 4){
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
callback(xhr.responseText);
}
else{
alert('Request was unsuccessful: ' + xhr.status);
}
}
}
url = url + serialize(options);
xhr.open(url,url,true);
xhr.send(null);
}

POST的封装

post函数是对Ajax的POST请求的封装,语法如下:
post(url, options, callback)
没有返回值,参数说明如下:
url:请求资源的url,String类型
options:请求的查询参数,Object类型
callback:回调函数,接收XMLHttpRequest对象的responseText属性作为参数,Function类型
使用示例如下:
post(‘/addUser’, {name: ‘jerry’, age: 1}, function(data) {
// 处理返回数据
});
请写出post函数的实现代码,要求浏览器兼容。

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(); //属性值转字符串
name = encodeURIComponent(name); //URI编码
value = encodeURIComponent(value); //URI编码
pairs.push(name + '=' + value); //属性名和属性值放入数组
}
return pairs.join('&');//返回字符串
}
function post(url, options, callback){
if(XMLHttpRequest){
var xhr=new XMLHttpRequest();//特性检测
}else{
var xhr=new ActiveXObject("Microsoft.XMLHTTP");//兼容
}
xhr.onreadystatechange = function(callback){ //处理返回数据
if(xhr.readyState == 4){
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
callback(xhr.responseText);
}
else{
alert('Request was unsuccessful: ' + xhr.status);
}
}
}
xhr.open('post','example,json',true);
xhr.send(serialize(formdata);
}