繁体   English   中英

如何创建具有变量值的 cookie

[英]How to create a cookie with a variable value

我需要创建一个 javascript cookie 以便对 PHP 做一些事情(确切地说,我需要获取浏览器的视口高度,将其存储在 javascript cookie 中以便获取 PHP 中的值)。 唯一的问题是我没有javascript的经验,也不明白google的解释。

我想在 cookie 中有这个值( var viewportHeight = $(window).height(); )。 但是怎么做?

(谷歌只给出了 static 值的例子)。

尝试这样的事情:

var viewportHeight = $(window).height();
document.cookie = "viewportheight=" + viewportHeight + ";";

您不能有 cookie 的动态值。 但是,您可以在每次 window 调整大小时更新 cookie:

$(function(){
   $(window).resize(function () { 
      createCookie( 'viewportHeight', $(window).height() );
   });
});

// You should also use some cross-browser cookie functions that make your life a lot easier
// function taken from: http://www.quirksmode.org/js/cookies.html
function createCookie(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 readCookie(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 eraseCookie(name) {
    createCookie(name,"",-1);
}

通过这种方式,您可以模拟 cookie 的“动态”值。 或者,您可以在每次浏览器调整大小时通过 ajax 将值发送到 php 脚本,而无需使用 cookies

对我来说似乎是个坏主意。 您的布局不应该要求服务器端的确切像素尺寸。 但是,如果你真的别无选择:

使用这个 jQuery 插件: https://github.com/carhartl/jquery-cookie

然后您可以执行以下操作:

// save the window height to a cookie whenever window is resized
$(window).resize(function(){
    $.cookie('viewportHeight', $(window).height(), {path:'/'});
});

// trigger the resize function so it saves the cookie on first load
$(window).load(function(){        
    window.setTimeout(function() {$(window).resize();}, 0);
}

然后在后续请求中从 PHP 访问它,如下所示:

$viewportHeight = $_COOKIE['viewportHeight'];

请注意,如果您在用户看到第一页之前需要 PHP 中的 cookie 值,这将不起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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