將HTML文件內容加載到Div [不使用iframe]

[英]Load HTML File Contents to Div [without the use of iframes]


I'm quite sure this a common question, but I'm pretty new to JS and am having some trouble with this.

我很確定這是一個常見的問題,但我對JS很新,我遇到了一些問題。

I would like to load x.html into a div with id "y" without using iframes. I've tried a few things, searched around, but I can't find a decent solution to my issue.

我想在不使用iframe的情況下將x.html加載到ID為“y”的div中。我嘗試了一些東西,搜索過,但我找不到合適的解決方案。

I would prefer something in JavaScript if possible.

如果可能的話,我更喜歡JavaScript中的東西。

Thanks in advance, everyone!

大家提前感謝!

5 个解决方案

#1


73  

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

哇,從所有框架促銷答案中你都會認為這是JavaScript難以置信的難題。這不是真的。

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

如果您需要IE <8兼容性,請首先執行此操作以使這些瀏覽器更快:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

請注意,使用腳本將內容加載到頁面中將使該內容對於沒有JavaScript可用的客戶端(例如搜索引擎)不可見。小心使用,如果您想要的只是將數據放在公共共享文件中,請考慮服務器端包含。

#2


64  

jQuery:

jQuery的:

$("#y").load("x.html");

#3


4  

I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:

我建議進入其中一個JS庫。它們可確保兼容性,因此您可以非常快速地啟動和運行。 jQuery和DOJO都很棒。例如,要做你在jQuery中嘗試做的事情,它會是這樣的:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>

#4


1  

    document.getElementById("id").innerHTML='<object type="text/html" data="x.html"></object>';

#5


0  

http://www.boutell.com/newfaq/creating/include.html

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

這將解釋如何編寫自己的客戶端,但jQuery是很多,更容易的選擇...加上你將通過使用jQuery獲得更多


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/08/20/72fcec55b961954f205c6c19333e5547.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com