如何在刷新后使用url hash加载特定页面?

Dan*_*uze 3 javascript ajax jquery

所以,我正在使用url哈希,这有助于我带来特定的内容hashchange.现在,当我在某些特定内容上并刷新整个页面时,我在网址中有了这个哈希值,但仍然没有得到该哈希表示的内容.

说我的网址是: http://localhost/user我点击了详细信息,它将我的网址转为以下内容: http://localhost/user#!details我正在查看详细信息页面.

但是当我重新加载页面时,将上面的内容作为我的url,哈希保持相同,并且哈希没有变化,它不会调用我与hashchange事件绑定的函数.

此外,每次用户重新加载时,我都无法在不发送ajax请求的情况下将哈希值提供给服务器端beforeunload.

有什么建议?

我的代码:

var pages = {};
pages['home'] = ""; pages['details'] = ""; pages['reviews'] = ""; pages['favs'] = "";
pages['likes'] = "", pages['gallery'] = "", pages['visited'] = "", pages['coupons'] = "";

$(window).bind('hashchange', function(event) {
    var curr_hash = event.target.location.hash;
    var page_to_load = curr_hash.substr(2);
    var loadurl = "/ci_theyaw/user/user_" + page_to_load;
    load_page(loadurl, page_to_load);
});

function load_page(page, toload){

    // alert(pages[toload]);

    if(pages[toload] == "") {
        var post_data = {
            '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
        };

        $.ajax({
            type: 'POST',
            url: page,
            data: post_data,
            dataType: "html",
            success : function(data) {
                page[toload] = data;
                $('.right-pane').html(data);
            },
            error : function(xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                console.log(xhr.responseText);
                alert(thrownError);
            }
        });
    }

    else {
        $('.right-pane').html(page[toload]);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 5

您需要运行附加到hashchange加载的代码,以防有人刷新页面,甚至直接将其键入浏览器.试试这个:

var hashUpdate = function(curr_hash) {
    var page_to_load = curr_hash.substr(2);
    var loadurl = "/ci_theyaw/user/user_" + page_to_load;
    load_page(loadurl, page_to_load);
}

$(window).bind('hashchange', function(e) {
    hashUpdate(e.target.location.hash);
}); 
window.location.hash && hashUpdate(window.location.hash); // onload, if there was a fragment in the URL
Run Code Online (Sandbox Code Playgroud)