将外部页面 html 插入页面 html

IT技术 javascript html
2021-03-17 18:44:44

我想将外部 html 页面加载/插入到我的网页中。例子 :

<b>Hello this is my webpage</b>
You can see here an interresting information :

XXXX

Hope you enjoyed

XXXX应该由一个小的脚本(尽可能小,因为),该负载像页替换http://www.mySite.com/myPageToInsert.html

我用 jquery 找到了以下代码:

<script>$("#testLoad").load("http://www.mySite.com/myPageToInsert.html");</script>    
<div id="testLoad"></div>

我希望不使用外部 javascript 库作为 jquery ......

3个回答

对此有 2 个解决方案(我至少知道 2 个):

  1. iframe -> 这个不太推荐

  2. 向所需页面发送 ajax 请求。

这是一个小脚本:

<script type="text/javascript">

function createRequestObject() {
    var obj;
    var browser = navigator.appName;
    if (browser == "Microsoft Internet Explorer") {
        obj = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        obj = new XMLHttpRequest();
    }
    return obj;
}

function sendReq(req) {   
    var http = createRequestObject();
    http.open('get', req);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

function handleResponse() {    
    if (http.readyState == 4) {
        var response = http.responseText;
        document.getElementById('setADivWithAnIDWhereYouWantIt').innerHTML=response;
    }
}

 sendReq('yourpage');
//previously </script> was not visible
</script>
这是最新的吗?
2021-04-16 18:44:44
收到此错误:未捕获的 ReferenceError:http 未定义
2021-04-28 18:44:44
如果您只需要它并且不想包含任何库,那么它仍然可以正常工作。尽管 js 库从那时起发生了很大的变化,所以我建议改用 jQuery ajax,因为它提供了更大的灵活性(5 年前你可能有很多理由不使用库......现在......呃......没有那么多;互联网发展到 100k 的库不是一个悲剧加载和不同库之间的大多数冲突是已知的并指出或修复)。
2021-04-29 18:44:44
必须添加此列表才能使其工作:http = createRequestObject()
2021-05-16 18:44:44

将一个IFRAME符合该法案?

<b>Hello this is my webpage</b>
You can see here an interresting information :

<iframe id="extFrame" src="http://www.mySite.com/myPageToInsert.html"></iframe>

Hope you enjoyed

您可以src使用普通的旧 javascript设置iframe 元素属性来切换另一个页面

Thx,我没有考虑 iframe 因为它有时在某些网站上有问题......但我应该重新考虑它。
2021-05-10 18:44:44

我认为您正在寻找的是 Jquery 源代码。

您可以在此处查看更多详细信息$(document).ready 等价物,无需 jQuery