简体   繁体   中英

Set cookie then redirect

The cookie is not holding and the domain example.com cannot redirect to a.example.com when I type on the address bar. Any help will be very much appreciated.

$(function(){
var city = getCookie('city');
if(city !=null && city !=''){
window.location.href = 'http://' + city + '.example.com';
}
$('#citygo').change(function(){
var city = $(this).val();
window.location.href = 'http://' + city + '.example.com';
});
});

<select id="citygo">
<option value="0">Select City</option>
<option value="amsterdam">Amsterdam</option>
<option value="newyork">New York</option>
<option value="london">London</option>
<option value="cardiff">Cardiff</option>
</select>

Is it like this? It is not working. Here is the code:

<script type="text/javascript" src="/static/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var cookieName = 'city';
var cookieValue = 'city';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + `";domain=.example.com;path=/;expires=" + myDate;
</script>

<script type="text/javascript">
//<![CDATA[
$(function(){
var city = getCookie('city');
if(city !=null && city !=''){
window.location.href = 'http://' + city + '.example.com';
}
$('#citygo').change(function(){
var city = $(this).val();
window.location.href = 'http://' + city + '.example.com';
});
});


function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function dropCookie(name) {
createCookie(name,"",-1);
}
//]]>
</script>

By default, cookies are set to only send on the same domain name that they came from. Be sure you set the cookie domain to .example.com to share across all subdomains (assuming that you indeed are trying to share across subdomains). /

 $.cookie('city', 'whatevercityhere', { expires: 7, path: '/', domain: '.example.com' });

Edit: Per comments below, also check that the cookie isn't set to http-only.

Try this example:

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
                  + ";domain=.example.com;path=/";
</script>

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