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>

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...