简体   繁体   中英

How to create a cookie with a variable value

I need to create a javascript cookie in order to do something with PHP (to be exactly, I need to get the viewport height of the browser, store that in a javascript cookie in order to get the value inside PHP). The only problem is I have no javascript experience, and I dont't understand google's explanation.

I'd like to have this value ( var viewportHeight = $(window).height(); ) inside a cookie. But how?

(google only gives examples with a static value).

try something like this:

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

You can't have dynamic values for a cookie. You can however update the cookie every time the window resizes:

$(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);
}

This way you can simulate "dinamic" values for a cookie. Alternatively, you can just send the value via ajax to a php script every time the browser resizes, without having to use cookies at all

Seems like a bad idea to me. Your layout shouldn't required the exact pixel dimensions on the server side. But, if you really have no other option:

Use this jQuery plugin: https://github.com/carhartl/jquery-cookie

Then you can do the following:

// 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);
}

Then you access it from PHP in subsequent requests like so:

$viewportHeight = $_COOKIE['viewportHeight'];

Please note that if you need the cookie value in PHP before the user sees the first page, this will not work.

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