GET方法封装:
XMLHttpRequest对象在大部分浏览器上已经实现而且拥有一个简单的接口允许数据从客户端传递到服务端,但并不会打断用户当前的操作
一般按照以下几个步骤:
1、建立XMLHttpRequest对象
2、注册回调函数
3、使用open方法设置和服务器交互的基本信息
4、设置发送的数据,开始和服务器交互
5、在回调函数中判断交互是否结束,响应是否正确,并根据需要获取服务器端返回的数据,更新页面内容。
方法
get(url, options, callback)
参数
- {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 get(url, options, callback) {
var xhr = new XMLHttpRequest();
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);
}
}
}
function serialize(options) {
if (!options) {
return '';
}
var pairs = [];
for (var name in options) {
if (!options.hasOwnProperty(name)) {
continue;
}
if (typeof options[name] === 'function') {
continue;
}
var value = options[name].toString();
name = encodeURIComponent(name);
value = encodeURIComponent(value);
pairs.push(name + '=' + value);
}
return pairs.join('&');
}
}
xhr.open('get', url+'?'+serialize(options),true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(null);
get('/information', { //数据验证
name: 'netease',
age: 18
},
function(data) {
console.log(data);
});
---------------------------post方式请求----------------------------
function post(url, options, callback) {
if(XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else{
var xhr=new ActiveXObject("Microsoft.XMLHTTP");//兼容ie
}
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);
}
}
}
function serialize(options) {
if (!options) {
return '';
}
var pairs = [];
for (var name in options) {
if (!options.hasOwnProperty(name)) {
continue;
}
if (typeof options[name] === 'function') {
continue;
}
var value = options[name].toString();
name = encodeURIComponent(name);
value = encodeURIComponent(value);
pairs.push(name + '=' + value);
}
return pairs.join('&');
}
}
xhr.open('post', url,true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(serialize(options));
post('/post', { //测试数据
name: 'netease-post',
age: 20
},
function(data) {
console.log('我是post请求');
});