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

jQuery實現(xiàn)跨域iframe接口方法調(diào)用

 更新時間:2015年03月14日 10:53:58   投稿:hebedich  
頁面a.html域名為www.a.com嵌入頁面http://www.b.com/b.html,b.html要調(diào)用a.html中的js函數(shù),由于兩個頁面不在一個域中,會提示沒權(quán)限。如何解決該問題呢,請看下面示例代碼。

cross.js

復(fù)制代碼 代碼如下:

(function(global){
  global.Cross = {
    signalHandler: {},
    on: function(signal, func){
      this.signalHandler[signal] = func;
    },
    call: function(win, domain, signal, data, callbackfunc){
      var notice = {"signal": signal, "data": data};
      if(!!callbackfunc){
          notice["callback"] = "callback_" + new Date().getTime();
          Cross.on(notice["callback"], callbackfunc);
      }
      var noticeStr = JSON.stringify(notice);
      win.postMessage(noticeStr, domain);
    }
  };
  $(window).on("message", function(e) {
    var realEvent = e.originalEvent,
        data = realEvent.data,
        swin = realEvent.source,
        origin = realEvent.origin,
        protocol;
    try {
        protocol = JSON.parse(data);
        var result = global.Cross.signalHandler[protocol.signal].call(null, protocol.data);
        if(!!protocol["callback"]){
          Cross.call(swin, origin, protocol["callback"], {result: result});
        }
        if(/^callback_/.test(protocol.signal)){
          delete Cross.signalHandler[protocol.signal];
        }
    } catch (e) {
      console.log(e);
      throw new Error("cross error.");
    }
  });
})(window);

a.html

復(fù)制代碼 代碼如下:

<!doctype HTML>
<html>
  <head>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="cross.js"></script>
    <script>
      function call_b(){
        var ifw = $("#ifr")[0].contentWindow;
        //調(diào)用iframe子頁面的公開的test接口, 子頁面域名為http://localhost:8088
        Cross.call(ifw,"http://localhost:8088","test",{t: $("#txt").val()});
      }
    </script>
  </head>
  <body>
    <input id="txt" type="text"/>
    <button onclick="call_b()">call</button>
    <iframe id="ifr" src="http://localhost:8088/b.html"></iframe>
  </body>
</html>

b.html

復(fù)制代碼 代碼如下:

<!doctype HTML>
<html>
  <head>
    <script src="jquery-1.8.3.min.js"></script>
    <script src="cross.js"></script>
    <script>
    //對外公開一個接口命名為test
    Cross.on("test", function(data){
      alert(data.t);
    });
    </script>
  </head>
  <body>
  </body>
</html>

以上就是本文所述的iframe跨域的解決方案了,希望大家能夠喜歡。

相關(guān)文章

最新評論