如果尚未设置,请使用JavaScript设置cookie

问题描述 投票:1回答:3

首先,请记住,我自己从未使用过Javascript(只使用了一些100%工作的脚本)和Objet编程相同(12年前在Pascal上学过程序)。

现在,我必须创建一个德语和法语的小网上商店。

我做了一些功能来设置保持选择语言的cookie。

但是现在,我想要至少一件事:如果没有任何名为“语言”的cookie,请创建一个并将其设置为法语。

我怎样才能做到这一点?

我的功能:

function setCookie(sName, sValue) {
var expDate = new Date();
expDate.setTime(expDate.getTime() + (365 * 24 * 3600 * 1000)); // ici 1 an
document.cookie = sName + "=" + escape(sValue) + ";expires=" + expDate.toGMTString() + ";path=/";
}

和页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <link href="./css/style.css" rel="stylesheet" media="all" type="text/css"  />
        <script type="text/Javascript" src="./javascript/cookie.js"></script>
        <title></title>
        <?php 
            require_once './includes/google_analytics.php';
        ?>
    </head>
    <body onload="setCookie('language','fr');">
    <p>
        Language : <a href="<?php echo $_SERVER['PHP_SELF']?>" onclick="setCookie('language','fr')">fr</a> /
        <a href="<?php echo $_SERVER['PHP_SELF']?>" onclick="setCookie('language','de')">de</a>
    </p>
    <?php       
        require_once './includes/menu.php';
    ?>

        <div id="contener">

        <!-- --------------------------------------------- -->    

    <?php 
        require_once './includes/header.php';
    ?>

        <!-- --------------------------------------------- --> 

        <!-- --------------------------------------------- --> 

    <?php 
        require_once './includes/footer.php';
    ?>

        </div>
    </body>
</html>

我想用“onload”进行测试。

javascript cookies isset
3个回答
0
投票

这将是检查cookie是否已设置的一种方法:

if (document.cookie.indexOf("language=") < 0)
    setCookie("language", "fr");

请注意,如果任何cookie的名称以language结尾,则也不会设置cookie。


编辑: 这是检查具有特定名称的cookie是否已存在的正确功能。

function cookieIsset(name)
{
    var cookies = document.cookie.split(";");
    for (var i in cookies)
    {
        if (cookies[i].indexOf(name + "=") == 0)
            return true;
    }
    return false;
}

你可以做到

if (!cookieIsset("language"))
    setCookie("language", "fr");

如何onload: 在您的<head>区域添加以下内容:

<script type="text/javascript">
document.onload = function () {
    // code ...
};
</script>

PHP解决方案: 因为OP最初有标签。

if (!isset($_COOKIE['language']))
    setCookie('language', 'fr');

0
投票

我知道这个答案看起来很长,但它有非常方便的实用方法。您可以使用这两种实用程序cookie方法 -

// Store the name/value pair as a cookie, encoding the value with
// encodeURIComponent() in order to escape semicolons, commas, and spaces.
// If daysToLive is a number, set the max-age attribute so that the cookie
// expires after the specified number of days. Pass 0 to delete a cookie.
function setCookie(name, value, daysToLive) {
    var cookie = name + "=" + encodeURIComponent(value);
    if (typeof daysToLive === "number")
    cookie += "; max-age=" + (daysToLive*60*60*24);
    document.cookie = cookie;
}

// Return the document's cookies as an object of name/value pairs.
// Assume that cookie values are encoded with encodeURIComponent().
function getCookies() {
    var cookies = {}; // The object we will return
    var all = document.cookie; // Get all cookies in one big string

    if (all === "") // If the property is the empty string
        return cookies; // return an empty object

    var list = all.split("; "); // Split into individual name=value pairs

    for(var i = 0; i < list.length; i++) { // For each cookie
        var cookie = list[i];
        var p = cookie.indexOf("="); // Find the first = sign
        var name = cookie.substring(0,p); // Get cookie name
        var value = cookie.substring(p+1); // Get cookie value
        value = decodeURIComponent(value); // Decode the value
        cookies[name] = value; // Store name and value in object
        }
return cookies;
}

然后 -

    /* a js function to check and set cookie */
function checkAndSetCookie(sName, sdefaultValue) {
    var cookies = getCookies();
    if(typeof(cookies[sName])==="undefined"){
        setCookie(sName, sdefaultValue, 365 * 24 * 3600 * 1000)
    }
}

将html更改为 -

<!-your html -->
<body onload="checkAndSetCookie('language','fr')">

要么

<!-- add just before body -->
<script type="text/javascript">
   checkAndSetCookie('language','fr');
</script>
<body>

0
投票

关键是你正在使用XHTML - 而在XHTML下,document.cookie是一个只读属性。 这意味着无论您尝试什么,都无法从JavaScript设置cookie。但是,设置cookie的可能方法是设置一个AJAX调用,将相关参数传递给后台脚本。然后可以使用所述后台脚本来设置cookie。

© www.soinside.com 2019 - 2024. All rights reserved.