使用AJAX/jQuery动态更改页面内容并设置哈希

Dynamically Change Page Content and Set Hash with AJAX/jQuery

本文关键字:哈希 设置 AJAX jQuery 动态 使用      更新时间:2023-09-26

我正在尝试创建一个网页,该网页将使用AJAX动态填充div。我已经能够用以下AJAX代码简单地更新div内容:

$(document).ready(function(){
    $("#projects-list a").click(function(e){ 
        e.preventDefault();
        var url = $(this).attr('href'); //get the link you want to load data from
        $.ajax({ 
            type: 'GET',
            url: url,
            success: function(data) { 
                $('#content').fadeOut(300, function() {
                    $('#content').html(data).delay(200).fadeIn(300);
                });
            } 
        }); 
    });
});

然而,我也希望找到一种方法来更新页面URL或更改哈希。例如,当用户获得/projects.html的链接时,他们将被发送到一个链接页面,然后当点击链接时,使用AJAX更改内容,url将更改为/projects.html#first。这样,用户导航到/projects.html#forest,他们将看到第一个项目的内容,而不是可供选择的项目的原始列表。

我建议使用库来处理URLpaths

http://github.com/flatiron/director

http://balupton.github.com/history.js/demo

如果你想使用标准#,那么你可以通过js在函数调用do上使用:window.location.hash = valueYouWantToSet,多数为部分ID,

然后你可以在页面加载时检查是否有#,然后调用一个特定的函数,比如:

handleHash: function () { if (!isNaN(parseInt(window.location.hash.replace('#', '')))){ this.showDetails(window.location.hash.replace('#', '')); }