2016-09-05 81 views
1

我從不同的頁面的服務器完整的HTML代碼接收爲字符串:設置動態內容的iframe

$.post($form.attr("action"), $form.serialize(), function(responseText) { 
     console.log("text received"); 

     //Setting dynamic content to iframe method * 

    }).error(function(p1, p2, p3){ 
     alert("error!"); 
     console.log(p1 + p2 + p3); 
    }) 

;

設置動態內容的iframe方法1:

var s = $(responseText); 
$('#FileFrame').contents().find('html').html(s); 

動態內容設置到的iframe方法2:

var $frame = $('#FileFrame'); 
    var doc = $frame[0].contentWindow.document; 
    var $body = $('body',doc); 
    $body.html(responseText); 

動態內容設置爲iframe中方法3:

var iframe = document.getElementById('FileFrame'); 
    var iframedoc = iframe.document; 
    if (iframe.contentDocument) 
    {  iframedoc = iframe.contentDocument; 
    console.log("iframe has contentDocument"); 
    } 
    else if (iframe.contentWindow) 
    { 
    iframedoc = iframe.contentWindow.document; 
    console.log("iframe has contentWindow.document"); 
    } 
    if (iframedoc) { 
    //iframedoc.open(); 
    iframedoc.write(responseText); 
    iframedoc.close(); 
    console.log("iframedoc is not NULL"); 
    } else { 
    alert('Cannot inject dynamic contents into iframe.'); 
    } 

的問題在於一些頁面顯示方法1很好,一些頁面顯示方法2,另一些則與我一起顯示thod 3,但他們中的任何一個都不會接近所有的網頁。 請幫助

+0

我覺得這個例子會做的工作[例1](http://stackoverflow.com/a/620905)嘗試解開//iframedoc.open();採用第三種方法。看來,第三種方法是最佳的 –

回答

0

嘗試修改你的第三個方法是這樣的:

var iframe = document.getElementById('FileFrame'); 
var iframeDoc; 
if(iframe.contentWindow){ 
    iframeDoc = iframe.contentWindow; 
} 
else if(iframe.contentDocument.document){ 
    iframeDoc = iframe.contentDocument.document; 
} 
else if (iframe.contentDocument) { 
    iframeDoc = iframe.contentDocument; 
} 
else{ 
    alert('Cannot inject dynamic contents into iframe.'); 
    return; 
} 
iframeDoc.document.open(); 
iframeDoc.document.write(responseText); 
iframeDoc.document.close(); 
+0

結果是一樣的一些頁面工作,一些沒有 – Geha