设置cookie然后重定向

时间:2013-12-03 05:22:08

标签: javascript redirect cookies

当我在地址栏上输入时,cookie未持有且域example.com无法重定向到a.example.com。任何帮助将非常感谢。

$(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>
这是这样的吗?它不起作用。这是代码:

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

2 个答案:

答案 0 :(得分:0)

默认情况下,Cookie设置为仅发送与其来源相同的域名。确保将cookie域设置为.example.com以在所有子域之间共享(假设您确实尝试跨子域共享)。 /

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

编辑:根据下面的评论,还要检查cookie是否设置为仅限http。

答案 1 :(得分:0)

试试这个例子:

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