这次给大家带来jQuery做出跨域iframe接口调用步骤详解,jQuery做出跨域iframe接口调用的注意事项有哪些,下面就是实战案例,一起来看一下。
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.
string
ify(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);<!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
onclick
="call_b()">call</button>
<iframe id="ifr" src="http://localhost:8088/b.html"></iframe>
</body>
</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>相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
以上就是jQuery做出跨域iframe接口调用步骤详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号