如何使用 JavaScript 调用 index.html:直接调用:使用 window.location.href 属性。相对路径导航:使用相对路径。使用 history.pushState:实现无缝加载。使用 AJAX:异步加载页面。

JS如何调用index.html
直接调用
最简单的方法是直接在JavaScript代码中使用window.location.href属性,例如:
<code class="js">window.location.href = 'index.html';</code>
相对路径导航
如果您希望相对于当前页面导航,可以使用相对路径:
<code class="js">window.location.href = './index.html';</code>
使用history.pushState
要无缝加载index.html页面,而不更改浏览器URL,可以使用history.pushState方法:
<code class="js">history.pushState(null, '', 'index.html');</code>
使用AJAX
如果您希望异步加载index.html页面,可以使用AJAX:
<code class="js">$.ajax({
url: 'index.html',
success: function(data) {
$('#content').html(data);
}
});</code>注意事项
- 如果您的网站在不同的域上托管,则无法使用直接调用或相对路径导航。
- 使用
history.pushState时,浏览器不会向服务器发出请求,因此您需要负责更新页面内容。 - 使用AJAX时,确保服务器配置了正确的跨域资源共享(CORS)标头。










