【问题标题】:Difference between cookie setting via serverside and client side通过服务器端和客户端设置 cookie 的区别
【发布时间】:2012-07-16 11:46:25
【问题描述】:
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”

【问题讨论】:

    标签: php javascript jquery zend-framework


    【解决方案1】:

    "有两个名为 foo 的 cookie"

    如果名称相同,则域必须不同。使用相同的域设置两个 cookie。请注意,example.netwww.example.net.example.net 不同。

    【讨论】:

    • 同域192.168.50.148
    • 因为一个域不能设置两个同名的cookies,所以一定有区别……
    猜你喜欢
    • 2011-10-18
    • 2018-11-04
    • 2018-07-24
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 2016-03-19
    相关资源
    最近更新 更多