手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >jQuery实现跨域iframe接口方法调用
jQuery实现跨域iframe接口方法调用
摘要:cross.js复制代码代码如下:(function(global){global.Cross={signalHandler:{},on:f...

cross.js

复制代码 代码如下:

(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

复制代码 代码如下:

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

//调用iframe子页面的公开的test接口, 子页面域名为http://localhost:8088

Cross.call(ifw,"http://localhost:8088","test",{t: $("#txt").val()});

}

</script>

</head>

<body>

<input id="txt" type="text"/>

<button>call</button>

<iframe id="ifr" src="http://localhost:8088/b.html"></iframe>

</body>

</html>

b.html

复制代码 代码如下:

<!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跨域的解决方案了,希望大家能够喜欢。

【jQuery实现跨域iframe接口方法调用】相关文章:

jQuery实现延迟跳转的方法

Jquery注册事件实现方法

jQuery预加载图片常用方法

jQuery实现在列表的首行添加数据

jQuery实现转动随机数抽奖效果的方法

jQuery实现返回顶部效果的方法

jQuery实现仿腾讯微博滑出效果报告每日天气的方法

JQuery自动触发事件的方法

jQuery实现给页面换肤的方法

JQuery中DOM实现事件移除的方法

精品推荐
分类导航