简体   繁体   English

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

[英]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!".您单击导航器“主页”,然后单击屏幕底部它会加载一个页面女巫文本,例如“Hello Word!”。

Does anybody know what to do?有人知道该怎么做吗? I'm pretty sure It involves JavaScript.我很确定它涉及 JavaScript。

To dynamically load content, you could make an AJAX call using XMLHttpRequest() .要动态加载内容,您可以使用XMLHttpRequest()进行 AJAX 调用。

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>

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 模板。

It's not necessary to use Ajax calls to load html.没有必要使用 Ajax 调用来加载 html。 Use them when need the server to process data successfully before loading the page, if processing was successful.如果处理成功,需要服务器在加载页面之前成功处理数据时使用它们。

If you don't have this concern, and you just want to load the html without data processing, a simple anchor tag will suffice:如果你没有这个顾虑,只想加载 html 而不进行数据处理,一个简单的锚标签就足够了:

 <a href="path/to/hello.html">click</a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM