1. 概述
1.1 問題描述
當報表嵌入在某個頁面 iframe 框架中時,如何在獲取主頁面裏定義的方法、如何獲取主頁面另外的内嵌 iframe 中的報表呢?即:
1)報表嵌入在某個頁面的 iframe 框架中,報表模板中如何獲取承載報表的 iframe 頁面裏定義的方法。
2)報表嵌入在某個頁面的 iframe 框架中,報表模板中如何獲取承載報表的 iframe 頁中嵌入的另一個 iframe 裏面的方法。
1.2 實現思路
首先通過 JavaScript 獲取方法所在的對象,然後通過方法名調用。
1)中頁面對於模板來說是父,因此可以通過 parent.window.fnname() 調用父頁面的方法。
2)中可通過父頁面獲取另一個 iframe,再調用其中的方法:parent.window.getElementById("iframename").contentWindow.fnname()。
2. 示例
2.1 準備HTML頁面
準備兩個 HTML 頁面 page1.html 和 page2.html,并保存在 %FR_HOME%\webapps\webroot\help 目錄下。如下圖所示:
如下 page1.html 中,通過 iframe 嵌入了一張 report 報表及 page2.html 頁面,在 page1 中定義了方法 fun1。
<html>
<head>
<title>page1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function fun1(){
alert("這是主頁面中的方法!");
}
</script>
</head>
<body>
<p>這是page1</p>
<iframe src="/webroot/help/page2.html" name="page2" id="page2" ></iframe>
<iframe src="/webroot/decision/view/report?viewlet=report.cpt" name="report" scrolling="auto"></iframe>
</body>
</html>
如下 page2.html 中,在 page2 中定義了方法 fun 2。
<html>
<head>
<title>page2</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function fun2(){
var name = alert("這是嵌在另一個iframe中頁面裏的方法!")
}
</script>
</head>
<body>
<P>這是page2!</p>
</body>
</html>
2.2 準備模板
新建模板 report.cpt ,模板的參數界面增加一個按鈕,按鈕「點擊」事件中,獲取頁面 page1 及 page2 中的方法。如下圖所示:
JavaScript 代碼如下:
var page1 = parent.window;
page1.fun1();
var page2 = page1.document.getElementById("page2").contentWindow;
page2.fun2();
2.3 效果預覽
打開浏覽器,輸入http://localhost:8075/webroot/help/page1.html,效果如 1.1 節預期效果所示: