Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to load another html file using JS

I'm trying to create a website, and I'm trying to figure out how to load a page.

For example:

You click on the navigator "Home" then a the bottom of the screen It loads a page witch text saying for example "Hello Word!".

Does anybody know what to do? I'm pretty sure It involves JavaScript.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

To dynamically load content, you could make an AJAX call using XMLHttpRequest().

In this example a url is passed to the loadPage() function, in which the loaded content is returned.

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript">
            function loadPage(href)
            {
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.open("GET", href, false);
                xmlhttp.send();
                return xmlhttp.responseText;
            }
        </script>
    </head>

    <body>
        <div onClick="document.getElementById('bottom').innerHTML = 
                      loadPage('hello-world.html');">Home</div>

        <div id="bottom"></div>
    </body>

</html>

When the div element containing text of "Home" is clicked, it sets the html of div element with id of "bottom" to content found in the "hello-world.html" document at the same relative location.

hello-world.html

<p>hello, world</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...