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