2016-09-05 80 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