欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解自定义ajax支持跨域组件封装

程序员文章站 2023-02-08 11:59:18
class.create()分析 仿prototype创建类继承 var class = { create: function () { v...

class.create()分析

仿prototype创建类继承

var class = {
  create: function () {
    var c = function () {
      this.request.apply(this, arguments);
    }
    for (var i = 0, il = arguments.length, it; i < il; i++) {
      it = arguments[i];
      if (it == null) continue;
      object.extend(c.prototype, it);
    }
    return c;
  }
};
object.extend = function (tobj, sobj) { 
  for (var o in sobj) {
    tobj[o] = sobj[o];
  }
  return tobj;
};

ajax定义:zip_ajax=class.create();

其中create方法返回的是一个构造函数request,这里相当于var zip_ajax= function(){ this.request.apply(this, arguments); }; 用对象冒充的方式在函数内部执行了一次构造的过程,相当于把构造函数任务交给了request方法,这里的this.request是zip_ajax的实例的方法,而this指向的就是zip_ajax的实例,apply后面的this指向的是zip_ajax,最后根据new关键字将this才真正指向zip_ajax类。有了类zip_ajax的定义,接下来就可以定义其方法:

xmlhttprequest详解:

xmlhttprequest不是一项技术而是一个内置于主流浏览器内的一个可以完全访问http协议的对象。传统的http请求大部分都是基于form提交请求http,然后返回一个form。xmlhttprequest支持同步请求的同时最大的优点就是支持异步传输接受数据,新建一个ajax请求实际就是实例化一个xmlhttprequest对象。简单介绍一下主要事件及方法:

readystatechange事件:

当xmlhttprequest发送一个http请求之后就会激发一个readystatechange事件,事件返回有五个值,0,1,2分别代表创建xmlhttprequest、初始化完成xmlhttprequest、发送了请求,3代表响应没结束(即只接收到响应头数据)4才是真正获得完整响应。

返回的status状态表示服务器返回的状态码:

常用的有200表示成功返回数据,301永久重定向,302为临时重定向(不安全)304读取的缓存数据400表示请求出现语法错误,403表示服务器拒绝请求,404表示请求网页资源不存在,405找不到指定位置服务器,408表示请求超时,500服务器内部错误,505表示服务器不支持请求的http协议版本。

200-300表示成功,300-400表示重定向,400-500表示请求内容或者格式或者请求体过大导致错误,500+表示服务器内部错误

open方法:

open接收三个参数分别是请求类型(get,post,head等)、url、同步或者异步

send方法:

当请求就绪后会触发send方法,发送的内容就是请求的数据(如果是get请求则参数为null;

请求成功之后会执行success自定义方法,其参数为返回数据;

ajax跨域:

什么是跨域?

如果两个站点www.a.com想向www.b.com请求数据就出现了因为域名不一致导致的跨域问题。即使是域名相同,如果端口不同的话也是会存在跨域问题(这种原因js是只能袖手旁观了)。判断是否跨域仅仅是通过window.location.protocol+window.location.host来判断例如http://www.baidu.com.

js解决跨域问题几种方案?

1、document.domain+iframe

对于主域相同而子域不同的请求可以使用域名+iframe作为解决办法。具体思想是假如有两个域名下的不同ab文件www.a.com/a.html

以及hi.a.com/b.html,我们可以在两个html文件中加上document.domain="a.com",之后通过在a文件中创建一个iframe去控制iframe的contentdocument,这样两个文件就可以对话了。举例如下:

www.a.com上的a.html文件中

document.domain="a.com";
  var selfframe=document.createelement("iframe");
  selfframe.src="http://hi.a.com/b.html";
  selfframe.style.display="none";
  document.body.appendchild(selfframe);
  selfframe.onload=function(){
    var doc=selfframe.contentdocument||selfframe.contentwindow.document;//得到操作b.html权限
    alert(doc.getelementbyid("ok_b").innerhtml());//具体操作b文件中元素
  }

hi.a.com上的b.html文件中

document.domain="a.com";

问题:

1、安全性,当一个站点(hi.a.com)被攻击后,另一个站点(www.a.com)会引起安全漏洞。2、如果一个页面中引入多个iframe,要想能够操作所有iframe,必须都得设置相同domain。

2、动态创建script(传说中jsonp方式)

浏览器默认禁止跨域访问,但不禁止在页面中引用其他域名的js文件,并且可以执行引入js文件中的方法等,根据这点我们可以通过创建script节点方法来实现完全跨域的通信。实现步骤为:

a.在请求发起方页面动态加载一个script,script的url指向接收方的后台,该地址返回的javascript方法会被发起方执行,url可以传参并仅支持get提交参数。

b.加载script脚本时候调用跨域的js方法进行回调处理(jsonp)。

举例如下:

发起方

function uploadscript(options){
  var head=document.getelementsbytagname("head")[0];
  var script=document.createelement("script");
  script.type="text/javasctipt";
  options.src += '?callback=' + options.callback;
  script.src=options.src;
  head.insertbefore(script,head.firstchild);
}
function callback(data){}
window.onload=function(){//调用
  uploadscript({src:"http://e.com/xxx/main.ashx",callback:callback})
}

接收方:

接收方只需要返回一个执行函数,该执行函数就是请求中的callback并赋参数。

3、使用html5的postmessage:

html5新功能有一个就是跨文档消息传输,如今大部分浏览器都已经支持并使用(包括ie8+),其支持基于web的实时消息传递并且不存在跨域问题。postmessage一般会跟iframe一起使用。

举例如下:

父页面:

<iframe id="mypost" src="http//www.a.com/main.html"></iframe>
window.onload=function(){
  document.getelementbyid("mypost").contentwindow.postmessage("显示我","http://www.a.com")
  //第二个参数表示确保数据发送给适合域名的文档
}
a.com/main.html页面:
window.addeventlistener("message",function(event){
  if(event.origin.indexof("a.com")>-1){
    document.getelementbyid("textarea").innerhtml=event.data;
  }
},false)
<body>
  <div>
    <span id="textarea"></span>
  </div>
</body>

这样在父页面加载完成后main.html页面的textarea部分就会显示"显示我"三个字

ajax方法封装code:

zip_ajax.prototype={
  request:function(url options){
    this.options=options;
    if(options.method=="jsonp"){//跨域请求
      return this.jsonp();
    }
    var httprequest=this.http();
    options=object.extend({method: 'get',
      async: true},options||{});
    
    if(options.method=="get"){
      url+=(url.indexof('?')==-1?'?':'&')+options.data;
      options.data=null;
    }
    httprequest.open(options.method,url,options.async);
    if (options.method == 'post') {
      httprequest.setrequestheader('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
    }
    httprequest.onreadystatechange = this._onstatechange.bind(this, httprequest, url, options);
    httprequest.send(options.data || null);//get请求情况下data为null
    return httprequest;
  },
  jsonp:function(){
    jsonp_str = 'jsonp_' + new date().gettime();
    eval(jsonp_str + ' = ' + this.options.callback + ';');    
    this.options.url += '?callback=' + jsonp_str;
    for(var i in this.options.data) {
      this.options.url += '&' + i + '=' + this.options.data[i];
    } 
    var doc_head = document.getelementsbytagname("head")[0],
      doc_js = document.createelement("script"),
      doc_js.src = this.options.url;
    doc_js.onload = doc_js.onreadystatechange = function(){
       if (!this.readystate || this.readystate == "loaded" || this.readystate == "complete"){
         //清除js
         doc_head.removechild(doc_js);      
        }
      }   
      doc_head.appendchild(doc_js);
  },
  http:function(){//判断是否支持xmlhttp
    if(window.xmlhttprequest){
      return new xmlhttprequest();
    }
    else{
      try{
        return new activexobject('msxml2.xmlhttp')
      }
      catch(e){
        try {
          return new activexobject('microsoft.xmlhttp');
        } catch (e) {
          return false;
        }
      }
    }
  },
  _onstatechange:function(http,url,options){
    if(http.readystate==4){
      http.onreadystatechange=function(){};//重置事件为空
      var s=http.status;
      if(typeof(s)=='number'&&s>200&&s<300){
        if(typeof(options.success)!='function')return;
        var format=http;
        if(typeof(options.format)=='string'){//判断请求数据格式
          switch(options.format){
            case 'text':
              format=http.responsetext;
              break;
            case 'json':
              try{
                format=eval('('+http.responsetext+')');
              }
              catch (e) {
                if (window.console && console.error) console.error(e);
              }
              break;
            case 'xml':
              format=http.responsexml;
              break;
          }
        }
      options.success(format);//成功回调
      }
      else {//请求出问题后处理
        if (window.closed) return;
        if (typeof (options.failure) == 'function') {
          var error = {
            status: http.status,
            statustext: http.statustext
          }
          //  判断是否是网络断线或者根本就请求不到服务器
          if (http.readystate == 4 && (http.status == 0 || http.status == 12030)) {
            //  是
            error.status = -1;
          }
          options.failure(error);
        }
      }
    } 
  }
};

使用方法:

ajax调用举例:

var myajax=new zip_ajax("http://www.a.com/you.php",{
  method:"get",
  data:"key=123456&name=yuchao",
  format:"json",
  success:function(data){
    ......
  }
})
跨域请求调用举例:
var jsonp=new zip_ajax("http://www.a.com/you.php",{
  method:"jsonp",
  data:{key:"123456",name:"yuchao"},
  callback:function(data){
    ......
  }
})