使用.htaccess重写可以轻松解决此问题。
演示:
A. 在 SERVER 1 上创建一个名为“iframeContent/”的目录。
B. 在该目录中放置一个名为 index.php 的文件,其中包含:
<html>
<head></head>
<body>
<script type="text/javascript">
parent.check();
</script>
</body>
</html>
这是 iFrame 的内容。它将调用父级中的函数。
C. 在 SERVER 2 上创建一个名为“iframeTesting_without-htaccess/”的目录。
D. 在该目录中放置一个名为 index.php 的文件,其中包含:
<html>
<head></head>
<body>
<script type="text/javascript">
function check() {
alert("hello");
}
</script>
<iframe id="sidebnrId" name="sidebnr"
src="PATH-ON-SERVER-1/iframeContent/" frameborder="0"
height="500px" width="600px" scrolling="no"></iframe>
</script>
</body>
</html>
这只是父窗口的内容。请注意,iFrame 内容位于另一台服务器上(因为在 SERVER 1 上)。
E. 使用网络浏览器访问“PATH-ON-SERVER-2/iframeTesting_without-htaccess/” -> 没有任何反应:iframe 无法访问其父级的功能。
这是解决问题的方法
F. 在 SERVER 2 上创建另一个名为“iframeTesting_with-htaccess/”的目录。
G. 在该目录中放置一个名为 index.php 的文件,其中包含:
<html>
<head></head>
<body>
<script type="text/javascript">
function check() {
alert("hello");
}
</script>
<iframe id="sidebnrId" name="sidebnr"
src="content-iframe/" frameborder="0"
height="500px" width="600px" scrolling="no"></iframe>
</script>
</body>
</html>
这次 iFrame 不再直接指向 SERVER 1 上的内容,而是指向位于同一服务器 (SERVER 2) 上的中间虚构目录“content-iframe/”。
H. 在该目录中放置一个 .htaccess 文件,其中包含:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^content-iframe/$ PATH-ON-SERVER-1/iframeContent/ [R,NC,P]
该文件的作用是将对虚构目录的任何访问重定向到服务器 1 上的内容。
I. 再试一次,使用网络浏览器访问“PATH-ON-SERVER-2/iframeTesting_with-htaccess/”。这一次它会起作用。我希望它有所帮助:-)