【问题标题】:How to use the url hash to load a particular page after a refresh?刷新后如何使用 url 哈希加载特定页面?
【发布时间】:2013-11-11 10:35:45
【问题描述】:

所以,我正在使用 url 哈希来帮助我在 hashchange 上显示特定内容。现在,当我在某些特定内容上并刷新整个页面时,我在 url 中有那个哈希值,但仍然没有得到那个哈希值指示的内容。

说我的网址是: 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]);
    }
}

【问题讨论】:

  • 你为什么还在使用hashbangs?我们现在有pushState and friends
  • 得看看那个。谢谢!

标签: javascript jquery ajax


【解决方案1】:

您需要在加载时运行附加到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

【讨论】:

  • 是的,成功了!谢谢。你能否告诉我,如果我第一次将数据存储在页面变量中并从那里加载,为什么我的浏览器会向服务器发出另一个请求?
【解决方案2】:
$(function(){
    var curr_hash = window.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);
});

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2011-05-09
    • 2018-07-21
    • 2014-09-23
    • 2011-04-16
    • 1970-01-01
    相关资源
    最近更新 更多