2011-06-25 52 views
1

main.html中有這樣的代碼:獲取幀內容與jQuery

<iframe id="myframe" src="myframe.html"></iframe> 

,我這觸發代碼中main.html中:

alert($('#myframe').contents().find('#mypage').contents().find('html').html()); 

myframe.html有這樣的代碼:

<frameset> 
<frame id="mypage" src="mypage.html"> 
</frameset> 

的mypage.html具有所有這些代碼:

<!DOCTYPE HTML> 
<html> 
<head> 
</head> 
hello world! 
</html> 

我想從main.html中頁面內獲得的mypage.html的所有HTML代碼,但我失敗了。我做這件事的方式有什麼問題?

+0

請考慮您的提取確切的問題,並要求它。 「不能使它工作」不是一個問題。 – ayckoster

回答

0

從技術上講,我不認爲你可以這樣做的框架,因爲這將是一個安全問題。

如果你確實需要加載ajax,你可以加載內部框架的源代碼。但它肯定不會生活

0

首先你需要在main.html中包含jquery庫。 其次, 鉻返回一個錯誤:

Unsafe JavaScript attempt to access frame with URL file:///../myframe.html from frame with URL file:///../main.html. Domains, protocols and ports must match.

所以這是一個安全問題

+0

當兩個文件位於同一個域中時,這確實起作用。 – Jan

0

我面臨同樣的問題。

我能解決它。

在我的例子:

myframe = ReportFrameReportViewerControl 
mypage = report 

這是代碼來獲取HTML(注意,所有網站必須在同一個域):

function bla() 
{ 
    var str = 
    $(
      $(
       $("#ReportFrameReportViewerControl")[0].contentWindow.document 
      ) 
      .find("#report")[0].contentWindow.document 
     ).find("html").html() 
     ; 

     alert(str); 
} 

你可能需要將其放入到一個按鈕,你可以按下一次頁面加載:

<input type="button" value="test" onclick="bla();" /> 

此外,如果你想要自動獲取html在頁面加載完成後,您需要註冊myframe & mypage的onload函數。

像這樣(更換BLA setTableSize):

$(document).ready(function() 
{ 
    $('#ReportFrameReportViewerControl').load(function() 
    { 
     //setNewHeight(); 
     //alert("Loading"); 

     setTableSize(); 

     $(
      $("#ReportFrameReportViewerControl")[0].contentWindow.document 
     ) 
     .find("#report").load(function() 
     { 
      //alert("load report"); 
      setTableSize(); 
     } 
     ); // End load #report 


    }); // End Function load #ReportFrameReportViewerControl 


}); // End Function document.ready