开发者

Jquery ajax hash return page fragment

开发者 https://www.devze.com 2022-12-21 03:17 出处:网络
I have an application with URLs like this: domain.com/category1/category2/ etc. I see that ajax understands the # and can pass the params to my php script. I am wondering if there is a way in ajax t

I have an application with URLs like this:

domain.com/category1/category2/ etc.

I see that ajax understands the # and can pass the params to my php script. I am wondering if there is a way in ajax to do the following URL:

domain.com/#category1/category2/

If so, is there a function that I can use in jquery to do this? I have seen jquery bbq but im a big confused how this helps me. It feels like there is an easier way, to just remove the hash and开发者_如何转开发 pass the remaining url to my php script, then return the page fragment?

How would I set up my php script to return the main page fragment without the header and footer being refreshed? Do I need to detect that # or javascript has been called and then return the relevant fragment?

i am trying it this way but its not posting the Ajax : hasher parameter.

<script>
hasher = document.location.hash;
hasher = hash.replace(/^.*#/, '');
$.ajax({ type: 'POST', url: url, data: {ajax:hasher}, dataType: 'html' }); 
</script>
<?php
echo $_POST['ajax'];
?>

Am I doing something wrong?

Cheers for any helps

Ke


You can get the hash value (after #) by getting document.location.hash property (this is standard property, not jQuery) and then pass it to the server-side script by calling $.ajax with some param like {hash:document.location.hash} in data.


Am I doing something wrong?

Yes.

  1. You are using hash var in second line instead of hasher.
  2. wrong regexp: you're trying to find anything BEFORE the #symbol, but you have just to remove # from the start of the document.location.hash
  3. Take a look into following example

    $('a.submit').click(function(){
        var hasher = document.location.hash;
        hasher = (hasher.length>0)?hasher.substr(1):'';
        $.ajax({
            type: 'POST', 
            url: '/test.php', 
            data: {ajax:hasher}, 
            dataType: 'html',
            success:function(response) {
                $('#ajax').html(response)
            }
        }); 
        return false;
    });
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号