将外部页面html插入页面html

Zit*_*tun 6 html javascript

我想在我的网页中加载/插入外部html页面.示例:

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

XXXX

Hope you enjoyed
Run Code Online (Sandbox Code Playgroud)

XXXX应该由一个小的脚本(尽可能小),该加载页面等代替http://www.mySite.com/myPageToInsert.html

我用jquery找到了以下代码:

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

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

zoz*_*ozo 7

有两个解决方案(至少我知道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>
Run Code Online (Sandbox Code Playgroud)