我们知道,每次根据不同接口,写不同的Ajax是一件比较麻烦的事儿,但是又不逃避他们,那么该肿么办呢,下面给大家介绍一种整合框架,可以根据与不同接口去创建不同的Ajax
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function ajax(option){
var setting = {
url:'',
method:'',
data:'',
async:true,
success:null,
error:null,
timeout:10000,
hrader:null,
dataType:'json'
};
//循环遍历传参
for(var p in option){
setting[p] = option[p]
}
//url后的数据处理
var requestdata = '';
if(typeof setting.data == 'object'){
var arr = [];
for(var p in setting.data){
arr.push(p + '=' + setting.data[p]);
}
requestdata = arr.join('&');
}else{
requestdata = setCharset.data;
}
//异步处理
var xhr;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject();
}
//get
if(setting.method.toLocaleLowerCase() == 'get'){
xhr.open(setting.method, setting.url +'?'+ requestdata, setting.async);
addHeader();
xhr.send();
}else{//post
xhr.open(setting.method, setting.url, setting.async);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
addHeader();
xhr.send(requestdata);
}
//是否超时
xhr.timeout = setting.timeout;
xhr.ontimeout = function(){
typeof setting.error == 'function' && setting.error('timer');
};
//报错
xhr.onerror = function(){
typeof setting.error == 'function' && setting.error(xhr.response);
};
//是否异步操作
if(setting.async){
xhr.onreadystatechange = function(){
doResult();
}
}else{
doResult();
}
//处理请求结果
function doResult(){
if(xhr.readyState == 4 && xhr.status == 200 && typeof setting.success == 'function');
{
switch (setting.dataType){
case 'json':
setting.success(JSON.parse(xhr.response));
break;
default :
setting.success(xhr.response);
}
}
}
//添加请求头
function addHeader(){
if(typeof setting.hrader == 'object'){
for(var p in setting.header){
xhr.setRequestHeader(p, setting.header[p]);
}
}
}
}
ajax({
url:'http://apis.baidu.com/tianyiweather/basicforecast/weatherapi',
method:'get',
data:'area=101010100',
dataType:'json',
header:{'apikey':'1b9e66408b7e243dcc6c3e10ef6e94d5'},
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
})
</script>
</body>
</html>