DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML和Xhtml
iframe 刷新的三種實作方案
編輯:HTML和Xhtml     

先準備一個 iframe:

<iframe src="1.htm" name="ifrmname" id="ifrmid"></iframe>

方案一:用 name 屬性定位

<input type="button" name="Button" value="Button" onclick="document.frames('ifrmname').location.reload()">

或

<input type="button" name="Button" value="Button" onclick="document.all.ifrmname.document.location.reload()">

方案二:用 id 屬性定位

<input type="button" name="Button" value="Button" onclick="ifrmid.window.location.reload()">

終極方案:跨域時

當 iframe 的 src 指向其他網站(跨域操作)時:

<input type="button" name="Button" value="Button" onclick="window.open(document.all.ifrmname.src,'ifrmname','')">

三個方案的差別在於「定位方式」與「能否跨域」。方案一、二都是同源情境下的做法,差別只是一個用 name、一個用 id;但要注意 document.frames 與 document.all 都屬於舊式 IE 語法,在現代瀏覽器中建議改用標準寫法:document.getElementById('ifrmid').contentWindow.location.reload()。

跨域之所以麻煩,是因為瀏覽器的同源政策會阻擋父頁讀取子頁的 document,reload() 自然無從呼叫。終極方案繞過的方式是「用 window.open 重新開一次同一個 src」,效果上看起來像刷新,但本質上是另開視窗。若真要跨域刷新,正確做法有兩條:一是直接重設 iframe 的 src(src 的設定不受同源政策限制,只是讀取被禁止),可視情況在網址後串時間戳避免快取;二是改用 postMessage 通知子頁自行處理。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved