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 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;
}
$(document).ready(function(){
alert(getCookie('foo'));
setCookie('foo','test'); //just setting a cookie on page load
$('#bing').click(function(){
$('#frm1').submit();
});
});
HTML side(foo.phtml)
<a href="javascript:void(0);" id="bing">Go</a>
<form id="frm1" method="POST" action="/somecontroller/someaction">
<input type="hidden" name="foo_post" value="this is from post" />
</form>
//服务器端
public function someactionAction(){
$_COOKIE['foo'] = $this->_request->getPost('foo_post');
$this->_redirect('/somecontroller/foo');
}
我的问题是在第一次加载页面时alert
返回 null,因为未设置 cookie,如果我再次刷新,将获得alert
“测试”,但如果我单击锚标记,则会发生表单提交并重写 cookie 值因为“这是来自帖子”,所以很明显在操作返回页面后会收到“这是来自帖子”的警报,但我仍然收到警报“测试”,cookie 值没有被重写
在我的 mozilla cookie 控制台中,有两个名为 foo 的 cookie,其值为“test”和“this is from post”