我找到了一种方法,可以使用在不刷新页面的情况下更改页面url
window.history.pushState
但我无法登录页面,也无法在不同的浏览中打开它,我得到了一个错误页面,找不到
例如:
www.mydomain.com/profile
我想登录此链接并进入个人资料页面。我该怎么办。
<script>
$(document).ready(function(){
//set trigger and container
var trigger = $('#nav ul li a'),
container = $('#container');
//do on click
trigger.on('click', function(e){
/***********/
e.preventDefault();
//get the link location that was clicked
pageurl = $(this).attr('href');
//to change the browser URL to th if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
/* reload content without refresh */
//set loading img
$('#container').append('<div id = "loading">WAIT... <img src = "img/ajax-loader-small.gif" alt="Currently loading" /></div>');
//change img location to center
$("#loading").css({"position": "absolute", "left": "50%", "top": "50%"});
//get the trigger to reload the contents
var $this = $(this),
target = $this.data('target');
container.load(target + '.php');
return false;
});
});
// fix url in the browser when click on backward and foreword arrows
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab',success: function(data){
$('#content').html(data);
}});
});
</script>
您需要确保您的web服务器(例如Apache或Nginx)接受对该URL的请求并正确重定向。有很多方法可以做到这一点。例如,您的web服务器可以将所有或大多数请求重定向到一个中心PHP文件,该文件将进一步路由请求。这通常优选在更复杂的系统中。然而,对于更简单的情况,使用mod_rewrite之类的东西可能就足够了(如果您使用Apache作为web服务器)。
假设您的设置允许,在文档根目录中的.htaccess文件中放入以下内容将导致mod_rewrite将所有请求转发到www.mydomain.com/profile
到www.mydomain.com/profile.php
:
RewriteEngine on
RewriteRule "^/profile$" "profile.php" [L]
这是一个非常简单的例子,只适用于特定的页面,但如果你有很多页面遵循相同的命名标准,你也可以应用更通用的规则。
如果您使用的是Apache以外的东西来为您的页面提供服务,那么几乎所有这些东西都有类似的功能。