使用HTML5历史记录时如何处理页面刷新?

时间:2011-12-30 03:53:52

标签: javascript html5 pushstate history.js

我已经阅读了大量的教程和示例无济于事,这使我在这里提出我的问题。我正在开发一个带有固定侧导航和动态内容div的网页。

问题

当我点击链接时,我们说'加载',内容div将显示我的其他页面'loadcourses.php'中的内容,然后使用历史记录api我将更改网址为'http://mydomain.com /main.php?page=loadcourses'。基本上main.php不会改变我只会添加另一页的标题并将其标记为链接后面的参数。

接下来,从动态加载的内容中,我有一些链接可以在点击时显示每个单独课程的内容。关键部分在于,一旦我点击任何链接,我应该解析另一个参数到下一页'course.php'。我设置了我的href ='http://mydomain.com/course.php?cid = CSC101'。现在我第一次加载动态div加载内容并成功检索下一页的id CSC101没有问题。但是当我点击刷新时,我的cid就丢失了。

根据历史记录api,后退/前进按钮正常工作。需要帮助,谢谢!!我目前正在研究这个.jsp原型。

document.addEventListener('DOMContentLoaded', init, false);

function hasBrowserHistory(){return !!(window.history && history.pushState);}
function updateHistory(url, replaceHistory) {
//Create a page path
var path  = "?page=" + url.split(".")[0];
var object = {
        data: url
    };

if(replaceHistory){
    //alert('as');
    /* 
    If this is the first page we are loading
    replace the current history item.
    */
    history.replaceState(object, null, path);
}else{
    //alert('qw');
    /*
    If we got here by clicking one of the links
    add a new item to the browser history
    */
    history.pushState(object, null, path);
}
}

function loadPage(whichPage, replaceHistory) {
$('#contentCol').load(whichPage);
updateHistory(whichPage, replaceHistory);
}

function historyPopStateHandler(e) {
//var state = history.state;
if (e.state == null) {
    alert(e.state.url);
}
if(e.state != null) {
    loadPage(e.state.data, true);
}
}

function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}

function init() {
//Check if the history API is available
if(!hasBrowserHistory()){
    alert('Sorry dude, your browser does not support the history API');
    return;
}       

//Check if we have any url params (e.g bookmark or reload)
var params = getUrlVars();

if(params['page'] != undefined && params['page'] != null){
    //Load the holder page with the correct content
    loadPage(params['page'] + ".jsp", true);
}else{
    //Load the default page
    loadPage('loadcourses.jsp', true);
}


//Setup listeners for the links
jQuery('nav > a').click(function(e){
    e.preventDefault();
    loadPage(jQuery(e.target).attr('href'), false);
});

//Setup listeners for the history events
window.addEventListener('popstate', historyPopStateHandler);
}

1 个答案:

答案 0 :(得分:0)

是的,我听到同样的问题,但我修好了......它如此简单,当你点击刷新时,浏览器将从服务器请求页面,页面不会在那里。 .. 为了满足这个需要你需要一个.htaccess文件,用于将这些请求重定向到相应的php文件...就像网址是www.you.com/coding一样,.htaccess文件将扫描单词编码,将请求重定向到coding.php ... 在php里面,你需要获取请求的$ @SERVER ['REQUEST_URI']然后做一些过滤...... 如果请求满足过滤器...在php上嵌入了一个html页面     BLA ..     ?&GT;

所以在html中添加了在加载表单时会出现的值......这就是我甚至在我的网站deenze中尝试过的逻辑并且它有效

相关问题