gpt4 book ai didi

javascript - php中的静态标题布局

转载 作者:行者123 更新时间:2023-11-29 17:56:09 26 4
gpt4 key购买 nike

我想知道如何在不刷新标题的情况下重新加载内容。我在下面创建了一个小示例代码。

Header.php

<html>
<head>
</head>
<body>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="index2.php">News</a></li>
</ul>

index.php

    <?php 
include("header.php");
?>
<div>
This is contents 1
</div>
</body>
</html>

index2.php

<?php 
include("header.php");
?>
<div>
This is contents 2
</div>
</body>
</html>

我假设 index 和 index2 页面是内容页面。

当我点击主页或新闻链接时,内容页面加载,但每次点击时 header.php 也会刷新。

我想知道,如何在单击主页链接时加载内容页面而不获取新鲜的 header.php。

有没有用 php 或 javascripts 做的想法?

最佳答案

您将不得不使用 AJAX 来处理这类事情。您要做的本质上是 SPA(单页应用程序)。虽然使用简单的 AJAX 请求来获取局部 View 来构建您自己的 SPA 是可以的,但我建议您学习 React 或 Angular。

为了达到预期的效果,你可以在vanilla javascript中使用简单的XHR或者你可以使用jQuery的$.ajax, $.post, $.get 。如果您选择 jQuery,您将在整个应用程序中大量使用这种方法。

Master.php 文件-

<html>
<head>
</head>
<body>
<?php include 'header.php'; ?>
<div id="content">
</div>
</body>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script type="text/javascript" src="main.js">
</html>

content.php -

<div>
<p>Content 1 goes here</p>
</div>

header.php -

<div>
<ul class="navbar">
<li id="home">home</li>
<li id="content">content</li>
</ul>
</div>

main.js -

$( document ).ready(function() {
$.ajax({
url: "content.php",
cache: false
})
.done(function( html ) {
$( "#content" ).html( html );
});
});

这只是它如何工作的一般概念。我没有测试代码,请不要指望它能按原样运行。您需要在导航栏中的链接上使用 onclick 监听器来调用 AJAX 并呈现正确的局部 View 。

关于javascript - php中的静态标题布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38910121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com