我的网站结构如下:
public_html/
- index.php
- students.php
用户加载包含按钮的网站(索引.php)。单击此按钮时,AJAX 用于加载"学生.php"并显示给用户(就好像他们只是无缝地转到不同的页面一样)。这样做时,将运行以下 JavaScript:
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
这会向浏览器历史记录添加状态,并导致浏览器 URL 显示"example.com/students"而不是"example.com"。但是,如果用户此时要刷新,由于文件夹"students"实际上不存在,因此不会加载任何内容(404 未找到)。
我的问题是,如何让用户浏览器实际显示"index.php"并自动将他们带到学生页面。换句话说,用户刷新"example.com/students",实际发生的是用户被带到索引.php文件,AJAX 会自动将他们带到学生页面(就好像他们实际上刷新了页面一样)
注意:我知道我可以将 null 传递给"pushState()"中的 url 参数,但是这种 URL 行为是需要的,因为它允许用户快速跳转到页面(如果我能让它工作)
通过 AJAX 显示学生页面的完整代码如下:
/**
* Display students screen.
*/
function displayStudents(createState) {
if(typeof(createState)==='undefined') {
createState = true;
}
$("#container").css("width", $( window ).width());
$("#container").css("position", "fixed");
$("#container").animate({marginLeft: "-100%"}, ANIMATION_SPEED);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#container").css("margin-left", "100%");
$("#container").html(xmlhttp.responseText);
$("#container").animate({marginLeft: "0"}, ANIMATION_SPEED, null, function reset() {
$("#container").css("width", "100%");
$("#container").css("position", "relative");
});
if(createState) {
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
}
}
};
xmlhttp.open("GET", "students.php", true);
setTimeout(function() { xmlhttp.send(); }, ANIMATION_SPEED);
}
此处的大部分代码用于动画。
换句话说,用户刷新"example.com/students",实际发生的是用户被带到索引.php文件,AJAX 会自动将他们带到学生页面(就好像他们实际上刷新了页面一样)
pushState 的要点是,当您使用 JavaScript 转换页面的状态时,您提供了一个 URL,服务器可以使用该 URL 来传递一些 HTML,这些 HTML 将提供处于该状态的页面。
如果你总是要提供主页,然后用JavaScript转换它,那么只需使用hashbangs。 pushState
完全是这项工作的错误工具。
如果要使用 pushState,则可能的方法的伪代码实现将如下所示:
GET data needed for the page
IF `Accept` header prefers `application/json`
Output `Content-Type: application/json` header
Output data in JSON format
ELSE
Output `Content-Type: text/html` header
Pass data through the template for the page
Output template as HTML
您将在URL中使用students.php
而不是students
(或者您将students
解析为要运行的PHP代码)。
由于您使用的是原始 XMLHttpRequest,因此需要使用 setRequestHeader
来设置 Accept 标头。不过,您使用的是jQuery,因此您可以使用$.ajax
并将其传递dataType: "json"
。