欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2018年02月08日 13:57:35   投稿:laozhang  
本篇文章給大家詳細(xì)分析了自定義ajax支持跨域組件封裝相關(guān)的知識(shí)點(diǎn),對(duì)此有興趣的朋友參考學(xué)習(xí)下。

Class.create()分析

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

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)造的過程,相當(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類。有了類ZIP_Ajax的定義,接下來就可以定義其方法:

XMLHttpRequest詳解:

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

readystatechange事件:

當(dāng)XMLHttpRequest發(fā)送一個(gè)http請求之后就會(huì)激發(fā)一個(gè)readystatechange事件,事件返回有五個(gè)值,0,1,2分別代表創(chuàng)建XMLHttpRequest、初始化完成XMLHttpRequest、發(fā)送了請求,3代表響應(yīng)沒結(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表示請求出現(xiàn)語法錯(cuò)誤,403表示服務(wù)器拒絕請求,404表示請求網(wǎng)頁資源不存在,405找不到指定位置服務(wù)器,408表示請求超時(shí),500服務(wù)器內(nèi)部錯(cuò)誤,505表示服務(wù)器不支持請求的http協(xié)議版本。

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

open方法:

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

send方法:

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

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

ajax跨域:

什么是跨域?

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

js解決跨域問題幾種方案?

1、document.domain+iframe

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

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

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";

問題:

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

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

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

a.在請求發(fā)起方頁面動(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ù)就是請求中的callback并賦參數(shù)。

3、使用html5的postMessage:

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

舉例如下:

父頁面:

<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頁面:
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部分就會(huì)顯示"顯示我"三個(gè)字

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'){//判斷請求數(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 {//請求出問題后處理
        if (window.closed) return;
        if (typeof (options.failure) == 'function') {
          var error = {
            status: http.status,
            statusText: http.statusText
          }
          //  判斷是否是網(wǎng)絡(luò)斷線或者根本就請求不到服務(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){
    ......
  }
})
跨域請求調(diào)用舉例:
var jsonp=new ZIP_Ajax("http://www.a.com/you.php",{
  method:"jsonp",
  data:{key:"123456",name:"yuchao"},
  callback:function(data){
    ......
  }
})

 

相關(guān)文章

最新評(píng)論