开发者

How to set jquery cookie for a URL with Fragment?

开发者 https://www.devze.com 2023-04-10 00:49 出处:网络
I am using the jquery cookie plug-in https://github.com/carhartl/jquery-cookie. I saw this reference on how to build a URL with Fragment:

I am using the jquery cookie plug-in https://github.com/carhartl/jquery-cookie.

I saw this reference on how to build a URL with Fragment: AJAX Applications Crawlable

The final url rule looks like this:

localhost/site/search#!key__searchword&page=1
localhost/site/search#!key__searchword&page=2
localhost/site/search#!key__searchword&page=3

(original url should like this: localhost/site/search?_escaped_fragment_key=searchword&page=1)

Each above page has one button, I want to check:

  • If user never clicked, he/she can do the click,
  • If user has clicked, then add class voted for forbidden click again. 开发者_JS百科
  • I want set cookie for 7 days.

My javascript code:

$(document).ready(function(){
  $(".up").live('click',function() {
    $.cookie('up', 'vote', { expires: 7, path: '/', domain: 'http://127.0.0.1/site/' });
    var up = $.cookie('up');
    if (up == 'vote') {
        $(".up").addClass('voted');
    };
  });
});

In anycase, the jquery cookie does not work for me. How can I set the jquery cookie for a URL with Fragment?


Fragments are never sent to the server, so you cannot set a cookie for a fragment. You can only set a cookie for the path, and it defaults to the path up to the last forward slash I believe according to the RFC.


You should set the cookie after checking whether the cookie exists or not A basic implementation should look like this:

$(document).ready(function(){
  $(".up").live('click',function() {
    var up = $.cookie('upvote');
    var currentLoc = location.hash;
    if (up && up.indexOf(currentLoc) == -1) {
        $(this).addClass('voted');
    };
    else {
        var saveCookie = up ? up + currentLoc : currentLoc;
        $.cookie('upvote', saveCookie, { expires: 7, path: '/', domain: 'http://127.0.0.1/site/' });
        //rest of functions
    }
  });
});

The current location is retrieved through location.hash. If the location's hash already exists in the cookie, the Already voted routine is followed. Else, a cookie is updated.

Note that this script will prevent a user from voting for seven days, each time the cookie is updated. You can use the hash as a cookie name if you want to set the seven day penalty individually for each page.

0

精彩评论

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

关注公众号