简体   繁体   中英

Set cookie domain with Javascript variable

Im taking the domain from the HTML of the page using jQuery:

domainUrl = $("p.domain").text();

for the purposes of testing:

<p class="domain">.vl3.co.uk</p>

Which is also the domain Im testing the script on.

This then give an alert containing the correct domain:

alert(domainUrl);

I want to the use that variable to set the domain in a cookie:

set_cookie('visible', 'no', 2020, 1, 1, '/', '+domainUrl+');

Here is the set cookie function:

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;
}

Why doesnt the cookie domain get set?

I think the problem is how im using the domainUrl variable when setting the cookie?

It should be: set_cookie('visible', 'no', 2020, 1, 1, '/', domainUrl);

Pls, try this extension, it works, it comprises all that:

http://plugins.jquery.com/project/Cookie

Then you only have to write:

$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com' });

Use jquery Annex library

I think this is the best way to get and set cookies using jQuery:

// cookie [writes and reads cookies]

//set cookie
$.cookie('kittencookie', 'fluffy', {expires : 7});

//get cookie
var kittenCookieValue = $.cookie('kittencookie');

For more details see documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM