【问题标题】:URL hashchange problems with ajax loadingajax 加载的 URL hashchange 问题
【发布时间】:2012-10-31 17:26:33
【问题描述】:

我有一个通过 ajax 加载内容的功能性 wordpress 主题。我遇到的一个问题是,当直接加载页面时,ajax 脚本不再起作用。例如,链接结构如下所示,而在 www.example.com 上单击 about 页面链接后,链接变为 www.example.com/#/about。但是当我直接加载独立页面 www.example.com/about 时,从该页面单击的其他链接会变成 www.example.com/about/#/otherlinks。我从这个教程http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html 中稍微修改了代码。这是我的代码。感谢您的帮助。

jQuery(document).ready(function($) {
var $mainContent = $("#container"),
    siteUrl = "http://" + top.location.host.toString(),
    url = ''; 

$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
    location.hash = this.pathname;
    return false;
}); 

$(window).bind('hashchange', function(){
    url = window.location.hash.substring(1); 

    if (!url) {
        return;
    } 

url = url + " #ajaxContent"; 

    $mainContent.fadeOut(function() {
        $mainContent.load(url,function(){
            $mainContent.fadeIn();
        });        
      });
    });

  $(window).trigger('hashchange');

});

【问题讨论】:

    标签: javascript ajax wordpress url hashchange


    【解决方案1】:

    你所表达的问题并不容易解决。有多种因素处于危险之中,但归结为:

    • 对 URL 的任何更改都会触发页面重新加载
    • 唯一的例外是 URL 的哈希部分发生变化

    如您所知,网址 www.example.com/about/ 中没有哈希部分。因此,您的脚本不能更改此部分,否则会触发页面重新加载。
    了解这一事实后,您的脚本只会通过添加新的散列部分或修改现有的散列部分来更改 URL,而只保留 URL 的“路径名”部分。所以你会得到像 www.example.com/about/#/otherlinks 这样的 URL。

    现在,在我看来,有两种方法可以解决您的问题。

    首先,有一个API that can modify the whole URL pathame without reload,但是it's not available everywhere。使用此解决方案并回退到旧版浏览器的经典页面重新加载是 cleaner method

    否则,您可以强制页面重新加载一次以将 URL 重置为 www.example.com/ 并从良好的基础开始。这是执行此操作的代码:

    $(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() {
        location = location.assign('#' + this.pathname);
        return false;
    }); 
    

    请注意,如果您的站点不在路径名的根目录下,此脚本将不起作用。因此,要使其适用于 www.example.com/mysite/,您需要更改正则表达式。

    请告诉我进展如何。

    【讨论】:

    • 感谢您的回复,这些链接很棒,我会告诉您结果如何。
    • 如果这篇文章回答了您的问题,您可能希望通过单击复选标记将其标记为正确。谢谢~
    • 我最终选择了 history.js 并摆脱了所有的 hashchanges
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多