JavaScript使ifram跨域相互访问及与PHP通信的实例

时间:2021-05-26

iframe 与主框架相互访问方法

1.同域相互访问

假设A.html 与 b.html domain都是localhost (同域)
A.html中iframe 嵌入 B.html,name=myframe
A.html有js function fMain()
B.html有js function fIframe()
需要实现 A.html 调用 B.html 的 fIframe(),B.html 调用 A.html 的 fMain()

A.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///fdipzone"]']); } </script> </head> <body> <p>A.html main</p> <p><input type="button" value="exec iframe function" onclick="exec_iframe()"></p> <!-- same domain --> <!--<iframe src="B.html" name="myframe" width="500" height="100"></iframe>--> <!-- cross domain --> <iframe src="http://127.0.0.1/B.html" name="myframe" width="500" height="100"></iframe> </body> </html> B.html<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title> iframe window </title> <script type="text/javascript" src="json2.js"></script> <script type="text/javascript" src="FrameMessage.js"></script> <script type="text/javascript"> // iframe js function function fIframe(name, obj, arr){ var obj_p = JSON.parse(obj); var arr_p = JSON.parse(arr); var msg = "iframe function execute success\n\n"; msg += "name:" + name + "\n"; msg += "gender:" + obj_p.gender + "\n"; msg += "age:" + obj_p.age + "\n"; msg += "blog:" + arr_p[0] + "\n"; msg += "weibo:" + arr_p[1] + "\n"; alert(msg); } // exec main function function exec_main(){ // same domain //FrameMessage.exec('', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']); // cross domain FrameMessage.exec('http://localhost/execA.php', '', 'fMain', ['programmer', '{"first":"PHP","second":"javascript"}', '["EEG","NMG"]']); } </script> </head> <body> <p>B.html iframe</p> <p><input type="button" value="exec main function" onclick="exec_main()"></p> </body> </html>

execA.php 与 execB.php

<?php require 'FrameMessage.class.php'; $frame = isset($_GET['frame'])? $_GET['frame'] : ''; $func = isset($_GET['func'])? $_GET['func'] : ''; $args = isset($_GET['args'])? $_GET['args'] : ''; $result = FrameMessage::execute($frame, $func, $args); echo $result; ?>

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章