jQuery + Ajax Hash / History and more

柔情痞子 提交于 2019-12-03 03:46:40

So what are you having problems with? Setting the hash tag or handling the change of the hash?

Of course setting the hashes is simply a question of putting the hashes in links, for example <a href="www.voidsync.com/2010/#page">Link</a> but I'm guessing that's not your problem.

To actually do something with the hash, you must have a listener function that checks for example every 100ms has the hash changed and acts accordingly. A simple function could go like this:

$(function() {
    var current_hash = false;
    setInterval(function() {
        if(window.location.hash != current_hash) {
            current_hash = window.location.hash;
            $('#content').load("content.php?page="+current_hash);
        }        
    }, 100);    
});

That (untested) function would check every 100ms if the hash has changed, and if it has, then updates the page via Ajax.

This function also works on page load, so if user lands on the page with a link such as www.voidsync.com/2010/#images, the function will load the page 'images' automatically. So history and bookmarking works.

Hope that helps, just ask if you meant something else.

David

Based off Tatu's answer, I just changed a few things to make this work for me. It keeps a history, so back and forward buttons work good. Here's what I have,

$(function() {
var current_hash = false;
setInterval(function() {
    if(window.location.hash != current_hash) {
        current_hash = window.location.hash;
            if(current_hash=='#home'){
                var month = '9';
                var year ='2011';       
                $.ajax({
                    type: "POST",
                    url: "/home.php",
                    data: "data+here",
                    success: function(msg){
                        $('#div').html(msg);
                    }       
                });                     
            }
            else if(current_hash=='#edit'){
                $.ajax({
                    type: "POST",
                    url: "/edit.php",
                    data: "data+here",
                    success: function(msg){
                        $('#div').html(msg);
                    }       
                });             
            }
    }        
}, 100);

Then simply assign some hash's to the links href attribute;

                    <li><a href="#home">Home Page</a></li>
                <li><a href="#edit">Edit Page</a></li>

It's not a whole rewrite, just basically added some if statements to the same thing, but it may help someone out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!