微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

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

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

有什么建议?

我的代码

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]);
    }
}

解决方法:

您需要在加载时运行附加到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); // onl oad, if there was a fragment in the URL

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐