Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - Insert external page html into a page html

I'd like to load/insert an external html page into my web page. Example :

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

XXXX

Hope you enjoyed

the XXXX should be replaced by a small script (the smaller as possible) that load a page like http://www.mySite.com/myPageToInsert.html

I found the following code with jquery :

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

I would like the same without using an external javascript library as jquery...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are 2 solutions for this (2 that I know at least):

  1. Iframe -> this one is not so recommended

  2. Send an ajax request to the desired page.

Here is a small script:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...