簡體   English   中英

使用CORS和javascript將xhtml文件加載到div元素

[英]Load an xhtml file to a div element using CORS and javascript

我想將頁面從另一個域加載到頁面中的div元素。 我正在使用CORS,它可以正常工作,因為它顯示文件已加載到控制台日志中,但是我無法將其添加到div中。 這是我的代碼,以使其更清楚:

<script type="text/javascript">
    function createCORSRequest(method, url){
        var xhr = new XMLHttpRequest();
        if ("withCredentials" in xhr){
            xhr.open(method, url, true);
        } else if (typeof XDomainRequest !== "undefined"){
            xhr = new XDomainRequest();
            xhr.open(method, url);
        } else {
            xhr = null;
        }
        return xhr;
    }

    var request = createCORSRequest("get", "http://localhost:8080/test/header.xhtml");
    if (request){
        request.onreadystatechange = function() {
            if (request.readyState === 4) {
                if (request.status >= 200 && request.status < 400) {
                    var hpage = request.responseText;
                    document.getElementById("theader").innerHTML = hpage;
                } else {
                    alert("An error occured! Request Status: +"request.status);
                }
            }
        };
        request.send();
    }            
</script>    
<body>
    <div id="theader"></div>
</body>

如何在theader div中顯示已加載的頁面?

更新我發現這發生在firefox和chrome中,因為我使用本地主機。 它可以在ie中工作,但是只加載沒有CSS和圖像的文本。 知道如何將整個頁面加載到div中嗎? 我想我現在的問題是網頁是否會像使用iframe一樣加載CORS中的所有資源? 如果可以,怎么辦?

div元素旨在僅包含某些HTML元素:概括地說,您可以在body找到的元素。 但不是所有HTML元素,尤其不是htmlhead元素。 這就是為什么您的代碼不起作用的原因。

要解決您的問題,您要么需要使用iframe (但從您的問題看來這不是您想要的),要么將body元素的內容放入div中並解析head並將其加載到當前head中。

那樣的東西(未經測試):

var hpage = document.createElement("html");
hpage.innerHtml = request.responseText;

//Below you might want to write more robust code
//depending on the content of the response and how much you trust it
var head = hpage.getElementsByTagName("head")[0];
var body = hpage.getElementsByTagName("body")[0];
document.getElementById("theader").innerHTML = body.innerHTML;

//Now iterates over the children of head to find 
//the script and style elements, and you can append them to the head of the document
var currentHead = document.getElementsByTagName("head")[0];
var scripts = head.getElementsByTagName("script");
for (var i=0; i<scripts.length; i++) {
  currentHead.appendChild(scripts[i]);
}
//same thing for style elements, 
//you could even do that for all elements
//depending on what the response may contain

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM