溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

詳解自定義ajax支持跨域組件封裝

發(fā)布時(shí)間:2020-10-09 07:14:42 來(lái)源:腳本之家 閱讀:113 作者:laozhang 欄目:web開(kāi)發(fā)

Class.create()分析

仿prototype創(chuàng)建類(lèi)繼承

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方法返回的是一個(gè)構(gòu)造函數(shù)request,這里相當(dāng)于var ZIP_Ajax= function(){ this.request.apply(this, arguments); }; 用對(duì)象冒充的方式在函數(shù)內(nèi)部執(zhí)行了一次構(gòu)造的過(guò)程,相當(dāng)于把構(gòu)造函數(shù)任務(wù)交給了request方法,這里的this.request是ZIP_Ajax的實(shí)例的方法,而this指向的就是ZIP_Ajax的實(shí)例,apply后面的this指向的是ZIP_Ajax,最后根據(jù)new關(guān)鍵字將this才真正指向ZIP_Ajax類(lèi)。有了類(lèi)ZIP_Ajax的定義,接下來(lái)就可以定義其方法:

XMLHttpRequest詳解:

XMLHttpRequest不是一項(xiàng)技術(shù)而是一個(gè)內(nèi)置于主流瀏覽器內(nèi)的一個(gè)可以完全訪(fǎng)問(wèn)http協(xié)議的對(duì)象。傳統(tǒng)的http請(qǐng)求大部分都是基于form提交請(qǐng)求http,然后返回一個(gè)form。XMLHttpRequest支持同步請(qǐng)求的同時(shí)最大的優(yōu)點(diǎn)就是支持異步傳輸接受數(shù)據(jù),新建一個(gè)ajax請(qǐng)求實(shí)際就是實(shí)例化一個(gè)XMLHttpRequest對(duì)象。簡(jiǎn)單介紹一下主要事件及方法:

readystatechange事件:

當(dāng)XMLHttpRequest發(fā)送一個(gè)http請(qǐng)求之后就會(huì)激發(fā)一個(gè)readystatechange事件,事件返回有五個(gè)值,0,1,2分別代表創(chuàng)建XMLHttpRequest、初始化完成XMLHttpRequest、發(fā)送了請(qǐng)求,3代表響應(yīng)沒(méi)結(jié)束(即只接收到響應(yīng)頭數(shù)據(jù))4才是真正獲得完整響應(yīng)。

返回的status狀態(tài)表示服務(wù)器返回的狀態(tài)碼:

常用的有200表示成功返回?cái)?shù)據(jù),301永久重定向,302為臨時(shí)重定向(不安全)304讀取的緩存數(shù)據(jù)400表示請(qǐng)求出現(xiàn)語(yǔ)法錯(cuò)誤,403表示服務(wù)器拒絕請(qǐng)求,404表示請(qǐng)求網(wǎng)頁(yè)資源不存在,405找不到指定位置服務(wù)器,408表示請(qǐng)求超時(shí),500服務(wù)器內(nèi)部錯(cuò)誤,505表示服務(wù)器不支持請(qǐng)求的http協(xié)議版本。

200-300表示成功,300-400表示重定向,400-500表示請(qǐng)求內(nèi)容或者格式或者請(qǐng)求體過(guò)大導(dǎo)致錯(cuò)誤,500+表示服務(wù)器內(nèi)部錯(cuò)誤

open方法:

open接收三個(gè)參數(shù)分別是請(qǐng)求類(lèi)型(get,post,head等)、url、同步或者異步

send方法:

當(dāng)請(qǐng)求就緒后會(huì)觸發(fā)send方法,發(fā)送的內(nèi)容就是請(qǐng)求的數(shù)據(jù)(如果是get請(qǐng)求則參數(shù)為null;

請(qǐng)求成功之后會(huì)執(zhí)行success自定義方法,其參數(shù)為返回?cái)?shù)據(jù);

ajax跨域:

什么是跨域?

如果兩個(gè)站點(diǎn)www.a.com想向www.b.com請(qǐng)求數(shù)據(jù)就出現(xiàn)了因?yàn)橛蛎灰恢聦?dǎo)致的跨域問(wèn)題。即使是域名相同,如果端口不同的話(huà)也是會(huì)存在跨域問(wèn)題(這種原因js是只能袖手旁觀了)。判斷是否跨域僅僅是通過(guò)window.location.protocol+window.location.host來(lái)判斷例如http://www.baidu.com.

js解決跨域問(wèn)題幾種方案?

1、document.domain+iframe

對(duì)于主域相同而子域不同的請(qǐng)求可以使用域名+iframe作為解決辦法。具體思想是假如有兩個(gè)域名下的不同ab文件www.a.com/a.html

以及hi.a.com/b.html,我們可以在兩個(gè)html文件中加上document.domain="a.com",之后通過(guò)在a文件中創(chuàng)建一個(gè)iframe去控制iframe的contentDocument,這樣兩個(gè)文件就可以對(duì)話(huà)了。舉例如下:

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權(quán)限
    alert(doc.getElementById("ok_b").innerHTML());//具體操作b文件中元素
  }

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

document.domain="a.com";

問(wèn)題:

1、安全性,當(dāng)一個(gè)站點(diǎn)(hi.a.com)被攻擊后,另一個(gè)站點(diǎn)(www.a.com)會(huì)引起安全漏洞。2、如果一個(gè)頁(yè)面中引入多個(gè)iframe,要想能夠操作所有iframe,必須都得設(shè)置相同domain。

2、動(dòng)態(tài)創(chuàng)建script(傳說(shuō)中jsonp方式)

瀏覽器默認(rèn)禁止跨域訪(fǎng)問(wèn),但不禁止在頁(yè)面中引用其他域名的js文件,并且可以執(zhí)行引入js文件中的方法等,根據(jù)這點(diǎn)我們可以通過(guò)創(chuàng)建script節(jié)點(diǎn)方法來(lái)實(shí)現(xiàn)完全跨域的通信。實(shí)現(xiàn)步驟為:

a.在請(qǐng)求發(fā)起方頁(yè)面動(dòng)態(tài)加載一個(gè)script,script的url指向接收方的后臺(tái),該地址返回的javascript方法會(huì)被發(fā)起方執(zhí)行,url可以傳參并僅支持get提交參數(shù)。

b.加載script腳本時(shí)候調(diào)用跨域的js方法進(jìn)行回調(diào)處理(jsonp)。

舉例如下:

發(fā)起方

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(){//調(diào)用
  uploadScript({src:"http://e.com/xxx/main.ashx",callback:callback})
}

接收方:

接收方只需要返回一個(gè)執(zhí)行函數(shù),該執(zhí)行函數(shù)就是請(qǐng)求中的callback并賦參數(shù)。

3、使用html5的postMessage:

html5新功能有一個(gè)就是跨文檔消息傳輸,如今大部分瀏覽器都已經(jīng)支持并使用(包括ie8+),其支持基于web的實(shí)時(shí)消息傳遞并且不存在跨域問(wèn)題。postMessage一般會(huì)跟iframe一起使用。

舉例如下:

父頁(yè)面:

<iframe id="myPost" src="http//www.a.com/main.html"></iframe>
window.onload=function(){
  document.getElementById("myPost").contentWindow.postMessage("顯示我","http://www.a.com")
  //第二個(gè)參數(shù)表示確保數(shù)據(jù)發(fā)送給適合域名的文檔
}
a.com/main.html頁(yè)面:
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>

這樣在父頁(yè)面加載完成后main.html頁(yè)面的textArea部分就會(huì)顯示"顯示我"三個(gè)字

ajax方法封裝code:

ZIP_Ajax.prototype={
  request:function(url options){
    this.options=options;
    if(options.method=="jsonp"){//跨域請(qǐng)求
      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請(qǐng)求情況下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'){//判斷請(qǐng)求數(shù)據(jù)格式
          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);//成功回調(diào)
      }
      else {//請(qǐng)求出問(wèn)題后處理
        if (window.closed) return;
        if (typeof (options.failure) == 'function') {
          var error = {
            status: http.status,
            statusText: http.statusText
          }
          //  判斷是否是網(wǎng)絡(luò)斷線(xiàn)或者根本就請(qǐng)求不到服務(wù)器
          if (http.readyState == 4 && (http.status == 0 || http.status == 12030)) {
            //  是
            error.status = -1;
          }
          options.failure(error);
        }
      }
    } 
  }
};

使用方法:

ajax調(diào)用舉例:

var myAjax=new ZIP_Ajax("http://www.a.com/you.php",{
  method:"get",
  data:"key=123456&name=yuchao",
  format:"json",
  success:function(data){
    ......
  }
})
跨域請(qǐng)求調(diào)用舉例:
var jsonp=new ZIP_Ajax("http://www.a.com/you.php",{
  method:"jsonp",
  data:{key:"123456",name:"yuchao"},
  callback:function(data){
    ......
  }
})

 

向AI問(wèn)一下細(xì)節(jié)
推薦閱讀:
  1. ajax的封裝
  2. ajax跨域

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI