原生JavaScript封装Ajax
封装类(1):
function Ajax(type, url, data, success, failed){
// 创建ajax对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP')
}
var type = type.toUpperCase();
// 用于清除缓存
var random = Math.random();
if(typeof data == 'object'){
var str = '';
for(var key in data){
str += key+'='+data[key]+'&';
}
data = str.replace(/&$/, '');
}
if(type == 'GET'){
//open:启动请求以备发送
if(data){
xhr.open('GET', url + '?' + data, true);
} else {
xhr.open('GET', url + '?t=' + random, true);
}
xhr.send(null);//发送请求
} else if(type == 'POST'){
xhr.open('POST', url, true);
// 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
}
// 处理返回数据
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){//已经接收到全部数据,可以在客户端使用了
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){//响应的http状态码
success(xhr.responseText);
} else {
if(failed){
failed(xhr.status);
}
}
}
}
}
调用方法:
var sendData = {name:'asher',sex:'male'};
Ajax('get', 'http://www.56191.com', sendData, function(data){
console.log(data);
}, function(error){
console.log(error);
});
封装类(2)
function ajax(opt) {
opt = opt || {};
opt.method = opt.method.toUpperCase() || 'POST';
opt.url = opt.url || '';
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function() {};
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
var params = [];
for (var key in opt.data) {
params.push(key + ':' + opt.data[key]);
}
var postData = params.join('&');
console.log(postData);
if (opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
//设置请求头
xmlHttp.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
xmlHttp.setRequestHeader('Content-Type', 'application/json');
xmlHttp.setRequestHeader('Cache-Control', 'private');
xmlHttp.send(JSON.stringify(opt.data));
} else if (opt.method.toUpperCase() === 'GET') {
xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
opt.success(xmlHttp.responseText);
}
};
}
调用方法:
ajax({
method: 'post',
url: 'http://www.56191.com',
data: {
access_token: 12312,
shop_id: 123123
},
success: function(response) {
console.log(response);
}
});