javascript 如何使用JS加载另一个html文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18930361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:43:05  来源:igfitidea点击:

How to load another html file using JS

javascript

提问by Shaun

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!".

您单击导航器“主页”,然后单击屏幕底部它会加载一个页面女巫文本,例如“Hello Word!”。

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

有人知道该怎么做吗?我很确定它涉及 JavaScript。

回答by Jason Sturges

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

要动态加载内容,您可以使用XMLHttpRequest().

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

在这个例子中,一个 url 被传递给loadPage()函数,在该函数中返回加载的内容。

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

当单击包含“Home”文本的 div 元素时,它将 id 为“bottom”的 div 元素的 html 设置为在相同相对位置的“hello-world.html”文档中找到的内容。

hello-world.html

你好-world.html

<p>hello, world</p>

回答by Deblaton Jean-Philippe

Ok, what you are looking for is a single page application.

好的,您正在寻找的是单页应用程序。

There are plenty of technologies implementing it, but not that easy.

有很多技术可以实现它,但并不那么容易。

Here is a tutorial I followed for doing it : http://andru.co/building-a-simple-single-page-application-using-angularjs

这是我遵循的教程:http: //andru.co/building-a-simple-single-page-application-using-angularjs

If you want to go further with SPAs, you will certainly need angular templates.

如果您想进一步使用 SPA,您肯定需要 Angular 模板。