原生 JS 的 AJAX 方案

vihi3329 7年前
   <h2>原声js的ajax方案</h2>    <p>整理原声ajax设计方案原因如下:</p>    <ol>     <li>从资源合理利用的角度以及网站优化角度去想,每次为了那几个功能,去引用一个框架,不划算</li>     <li>拜读了w3c的ajax的设计方案,包括level1和level2的规范,有种豁然开朗的感觉</li>     <li>有朋友遇到ajax的跨域方案,各种纠结在心里,导致内心不能舒畅</li>     <li>自己的框架底层也要需要用到ajax的基础功能,(get post请求,对于level2的上传暂时没用到)</li>     <li>最关键的也是之前对这块概念十分模糊,所以开始整理ajax这块的设计方案</li>    </ol>    <p><strong>一些概念:</strong></p>    <ul>     <li>浏览器的同源策略:浏览器最基本的安全功能,同源是指,域名,协议,端口相同(所以我写的接口部署端口分别为1122和2211即不是同源,属于跨域)    </li>     <li>ajax:是一种技术方案,依赖的是CSS/HTML/Javascript,最核心依赖是浏览器提供的XMLHttpRequest对象,这个对象使得浏览器可以发出HTTP请求与接收HTTP响应。</li>     <li>nginx:是一个高性能的HTTP和反向代理服务器</li>     <li>IIS:微软开发的的服务器,window系统自带</li>     <li style="text-align:center">XMLHttpRequest 兼容性如下:       <img src="https://simg.open-open.com/show/fff78143fb292e9001cb0f67b3a6258e.png"></li>     <li>XMLHttpRequest Level 1主要存在以下缺点:      <ol>       <li>受同源策略的限制,不能发送跨域请求;</li>       <li>不能发送二进制文件(如图片、视频、音频等),只能发送纯文本数据;</li>       <li>发送和获取数据的过程中,无法实时获取进度信息,只能判断是否完成;</li>      </ol> </li>     <li>XMLHttpRequest Level 1主要存在以下缺点:      <ol>       <li>可以发送跨域请求,在服务端允许的情况下;</li>       <li>支持发送和接收二进制数据;</li>       <li>新增formData对象,支持发送表单数据;</li>       <li>发送和获取数据时,可以获取进度信息;</li>       <li>可以设置请求的超时时间;</li>      </ol> </li>    </ul>    <p><strong>开始准备如下:</strong></p>    <ul>     <li>纯前端代码</li>     <li>nginx反向代理服务器(前后端分离用)</li>     <li>后台2套接口(端口:1122,端口:2211) PS:一份必须支持跨域请求</li>     <li>IIS服务器(部署后台接口)</li>     <li>chrome插件postman(接口测试)</li>     <li>IE、chrome、firefox、Opera、safari、edge 6大浏览器,做兼容性测试</li>    </ul>    <h3><strong>XMLHttpRequest发送请求步骤:</strong></h3>    <ol>     <li>实例化XMLHttpRequest对象(IE8-9是微软封装的ActiveXObject('Microsoft.XMLHTTP'))获得一个实例</li>     <li>通过实例open一个请求,设置发送类型和接口以及同异步</li>     <li>如有需要配置报文,以及各种事件(success,error,timeout等)</li>     <li>IIS服务器(部署后台接口)</li>     <li>调用实例的send方法,发送http/https的请求</li>     <li>服务器回调,客户端接收,并做响应处理</li>    </ol>    <p><strong>核心代码:</strong></p>    <pre>  <code class="language-javascript">//创建xhr对象  var xhr = createXhrObject();    //针对某些特定版本的mozillar浏览器的BUG进行修正  xhr.overrideMimeType?(xhr.overrideMimeType("text/javascript")):(null);    //针对IE8的xhr做处理 PS:ie8下的xhr无xhr.onload事件,所以这里做判断  xhr.onload===undefined?(xhr.xhr_ie8=true):(xhr.xhr_ie8=false);    //参数处理(get和post),包括xhr.open     get:拼接好url再open   post:先open,再设置其他参数  ajaxSetting.data === ""?(null):(xhr = dealWithParam(ajaxSetting,this,xhr));    //设置超时时间(只有异步请求才有超时时间)  ajaxParam.async?(xhr.timeout = ajaxSetting.time):(null);    //设置http协议的头部  each(ajaxSetting.requestHeader,function(item,index){xhr.setRequestHeader(index,item)});  //onload事件(IE8下没有该事件)  xhr.onload = function(e) {      if(this.status == 200||this.status == 304){          ajaxSetting.dataType.toUpperCase() == "JSON"?(ajaxSetting.success(JSON.parse(xhr.responseText))):(ajaxSetting.success(xhr.responseText));      }else{          /*           *  这边为了兼容IE8、9的问题,以及请求完成而造成的其他错误,比如404等           *   如果跨域请求在IE8、9下跨域失败不走onerror方法           *       其他支持了Level 2 的版本 直接走onerror           * */          ajaxSetting.error(e.currentTarget.status, e.currentTarget.statusText);      }  };    //xmlhttprequest每次变化一个状态所监控的事件(可拓展)  xhr.onreadystatechange = function(){      switch(xhr.readyState){          case 1://打开              //do something              break;          case 2://获取header              //do something              break;          case 3://请求              //do something              break;          case 4://完成              //在ie8下面,无xhr的onload事件,只能放在此处处理回调结果              xhr.xhr_ie8?((xhr.status == 200 || xhr.status == 304)?(ajaxSetting.dataType.toUpperCase() == "JSON"?(ajaxSetting.success(JSON.parse(xhr.responseText))):(ajaxSetting.success(xhr.responseText))):(null)):(null);              break;      };  };    //ontimeout超时事件  xhr.ontimeout = function(e){      ajaxSetting.timeout(999,e?(e.type):("timeout"));   //IE8 没有e参数      xhr.abort();  //关闭请求  };    //错误事件,直接ajax失败,而不走onload事件  xhr.onerror = function(e){      ajaxSetting.error();  };    xhr.send((function(result){this.postParam == undefined?(result =null):(result=this.postParam);return result;})(this.postParam));</code></pre>    <p><strong>测试代码如下:</strong></p>    <p>前端同源测试代码</p>    <pre>  <code class="language-javascript">ajax.post("/api/ajax1/ajaxT1/",{"name":"测试异步post请求","age":"success"},function(data){alert(data)});  //该接口在1122上</code></pre>    <p>前端跨域测试代码</p>    <pre>  <code class="language-javascript">ajax.post_cross("http://192.168.0.3:2211/api/weixin/ajaxT2/",{"name":"测试跨域post请求","age":"success"},function(data){alert(data)});</code></pre>    <p>后端跨域接口代码</p>    <pre>  <code class="language-javascript">/// <summary>  /// 测试跨域请求  /// </summary>  /// <param name="module"></param>  /// <returns></returns>  [Route("ajaxT2")]  public String kuaAjaxT2([FromBody]TModule module)  {    String result = "跨域post传输成功:"+module.name+"-"+module.age;    return result;  }</code></pre>    <p>后端同源接口代码</p>    <pre>  <code class="language-javascript">/// <summary>  /// 测试ajax同源请求  /// </summary>  /// <param qwer="code"></param>  /// <returns>result</returns>  [Route("ajaxT2")]  public String GetkuaAjaxT1(string name,string age)  {      String result = "1J跨域成功:" + name + "-" + age;      return result;  }</code></pre>    <p>下面是各种浏览器的测试结果(仅提供同源post请求和跨域post请求):</p>    <p>同源测试</p>    <p><strong>chrome</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0bfcdf49a0948c49901d01598b7d996f.png"></p>    <p><strong>IE8-9</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/cbc98eaca8db336a92fad0293229df7e.png"> <img src="https://simg.open-open.com/show/b1b4f79c80af43e15713353751ddefed.png"></p>    <p><strong>IE10+</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/433ed41b5455aecad7c67b38ded86ef4.png"></p>    <p><strong>firefox</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/89b3e7f4bdb8854620bbcf84de5a5c7f.png"></p>    <p><strong>opera</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/5b6a83d88f07e19e15e9b54c9ad3fccc.png"></p>    <p><strong>safari</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/9d07a734e3cac9bee28564b416638d14.png"></p>    <p><strong>edge</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ac3947b15b03263a52eaa0378be8abcd.png"></p>    <p>跨域测试</p>    <p><strong>chrome</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/b487916794e5a3873a22e28abce0b0f8.png"></p>    <p><strong>IE8-9</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/bf372fe872c2b504228fdf58fd3fe148.png"> <img src="https://simg.open-open.com/show/4d13887d894f24eea7385d34aede489a.png"></p>    <p><strong>IE10+</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/988b993184a410c56584776f88a17ac4.png"></p>    <p><strong>firefox</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/410ccf7961541a0d72289e98c167cbc5.png"></p>    <p><strong>opera</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/a05090bd37660c6b4a43b6c143fa3569.png"></p>    <p><strong>safari</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/148e5844864d745e1a5d1d6447d4b354.png"></p>    <p><strong>edge</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/19261329c949034a034d33b6eaf8601e.png"></p>    <p>具体代码已封装成一个js库,供大家根据项目需求,自己开发定制,不过我已经封装了一些常用请求</p>    <ul>     <li>异步get请求 -- ajax.get</li>     <li>异步post请求 -- ajax.post</li>     <li>同步get请求 -- ajax.get_sync</li>     <li>同步post请求 -- ajax.post_sync</li>     <li>跨域get请求 -- ajax.get_cross</li>     <li>跨域post请求 -- ajax.post_cross</li>     <li>通用配置请求 -- ajax.common<br> PS:该方法为方便使用,不用的可以直接使用精简版本,只有common方法</li>    </ul>    <p> </p>    <p>来自:https://github.com/GerryIsWarrior/ajax</p>    <p> </p>