gpt4 book ai didi

javascript - 加载页面内容而不重新加载横幅

转载 作者:行者123 更新时间:2023-11-27 23:55:37 27 4
gpt4 key购买 nike

不久前,我有一个网站,当单击网址时会加载其某些部分。例如:

www.mysite.com/index.php 将变成 www.mysite.com/index?contact.php

anchor 看起来像 <a href="index?contact.php">Contact</a>

页眉、导航栏和页脚将不会再次加载,但“index”的内容将被“Contact”的内容替换

我只是不记得让 anchor 替换使用 anchor 请求的 PHP 文件加载的脚本。

索引文件看起来像这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>My Site</title>
<style>
<?php include 'css/styles.css'; ?>
</style>
</head>

<body>
<script here>
<a href="index?contact.php">Contact</a>
<a href="index?contact.php">Store</a>
<a href="index?contact.php">Stuff</a>
</body>
</html>

然后每个“php”文件将加载一组不同的:

<div id="div_1"></div>
<div id="div_2"></div>
<div id="div_3"></div>

这一切都来自一个 CSS。

我希望我足够清楚我要实现的目标,并且有人可以帮助我。

最佳答案

您可以通过使用 AJAX/XMLHttpRequest 来实现此目的。如果你不使用像 jQuery 这样的 js 库,纯 js 会是这样的:

function requestPage(requestPage) {
var xmlhttp = new XMLHttpRequest();
// what will we do with the response?
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("content").innerHTML = xmlhttp.responseText;
} else {
// page could not be loaded/requested
document.getElementById("content").innerHTML = "Page not found.";
}
}
// actuall request
xmlhttp.open("GET", requestPage, true);
xmlhttp.send();
}
var anchors = document.querySelectorAll("a");
for(var index = 0; index < anchors.length; index++) {
anchors[index].addEventListener("click", function (event) {
event.prefentDefault();
requestPage(event.target.href);
});
}

此代码假定您有一个 id 为“#content”的元素,页面内容应在其中加载。关于什么是可能的以及如何使用 js XMLHttpRequest 对象的一点引用:http://www.w3schools.com/ajax/default.asp

关于javascript - 加载页面内容而不重新加载横幅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32294728/

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