pushState
リクエストは行わず、URL を変更して新しい履歴エントリを保存するだけです。この概念について考えると、サーバーは常にリクエストを行うため、更新やブックマークは不可能です。サーバー側のソリューションが必要です。
数時間検索した後、私は解決策を見つけました.PHPindex.php
がリクエストを処理できるようにするには、すべての呼び出しをリダイレクトする必要があります.
rewrite ^/(.*)$ /index.php?page=$1 last
Web サイトを更新したり、ページをブックマークしたりするには、このファイルがどうあるべきか正確にはわかりません。誰かが私を助けることができますか?明確にするために例を作成しました。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>History API</title>
<script>
function ajax (url, callback) {
var conection = new XMLHttpRequest ();
conection.open ("GET", url, true);
conection.setRequestHeader ("X-Requested-With", "XMLHttpRequest");
conection.send (null);
conection.onreadystatechange = function () {
if (conection.readyState === 4) {
if (conection.status === 200) {
callback (conection.responseText);
}
else if (conection.status === 404) {
alert ("Page not found !");
}
else {
alert ("Error !");
}
}
}
}
window.addEventListener ("popstate", function (event) {
var state = event.state;
if (state) {
document.getElementById ("content").innerHTML = state["content"];
}
});
document.addEventListener ("DOMContentLoaded", function () {
var content = document.getElementById ("content");
var menu = document.getElementById ("menu");
menu.addEventListener ("click", function (event) {
var target = event.target;
if (target.nodeName === "A") {
ajax (target.href, function (result) {
history.pushState ({"content": result}, target.innerHTML, target.href);
content.innerHTML = result;
});
event.preventDefault ();
}
});
});
</script>
<style>
body {
width: 400px;
}
div {
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<div id = "menu">
<a href = "page1.html">Page 1</a>
<a href = "page2.html">Page 2</a>
</div>
<div id = "content"></div>
</body>
</html>
index.php
<?php
isset ($_GET["page"]) or exit ("Error !");
$page = $_GET["page"];
// Ajax request
if (isset ($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower ($_SERVER["HTTP_X_REQUESTED_WITH"]) === "xmlhttprequest") {
if (file_exists ($page)) {
require_once ($page);
}
else {
header ("HTTP/1.1 404 Not Found");
}
}
else {
require_once ("index.html");
}
?>
page1.html
こんにちは、ページ1です。はじめまして。
page2.html
こんにちは兄弟。私は2ページ目です。
クリック(OK)
リフレッシュ (失敗)