开发者

Javascript Cookie Function not working for Domain

Here are the functions Im using:

Set Cookie:

function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( exp_y )
  {
    var expires = new Date ( exp_y, exp_m, exp_d );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
        cookie_string += "; path=" + escape ( path );

  if ( domain )
        cookie_string += "; domain=" + escape ( domain );

  if ( secure )
        cookie_string += "; secure";

  document.cookie = cookie_string;
}

Read Cookie:

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

Delete Cookie:

function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

The Jquery I use to construct the cookie:

    if(get_cookie('visible')== 'no') {
        $("#wrapper").hide();
        $(".help").hide();
        $("#slid .show").show();
        $("#slid .hide").hide();
        } else {
            $("#slid .show").hide();
            $("#slid .hide").show();
        }
    $("#slider").click(function() {
        if(get_cookie('visible')== null) {
            set_cookie('visible','no', 2020, 01,01, '/', 'domain.com');
        } else {
            delete_cookie开发者_运维技巧('visible');
        }
            $(".help").slideToggle();
                $("#wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() {
                    $("#slid img").toggle();
                });
    });

Im trying to set the cookie for all pages that exist under domain.com with the path '/'.

However using these functions and jQuery it doesn't appear to be working, any anyone give me an idea of where im going wrong?


Works for me, as long as the domain is matching or omitted, and there's nothing in domain or path that gets mangled by escape().

(You shouldn't use escape() for the cookie parameters: there is no standard escaping scheme for these. It's generally a bad idea to use escape()/unescape() for anything; it's a non-standard encoding scheme that is not the same as URL-encoding, so if you try to read the cookie from some other language like PHP you won't be able to decode it properly using any built-in function. If you want real URL-encoding for the cookie values themselves, go for encodeURIComponent/decodeURIComponent, though again, these are still not used for cookie parameters.)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜