微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Ajax框架整合

我们知道,每次根据不同接口,写不同的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>

原文地址:https://www.jb51.cc/ajax/161884.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐