【问题标题】:Onclick Sets a Cookie For a Page [closed]Onclick 为页面设置 Cookie [关闭]
【发布时间】:2020-06-27 04:58:28
【问题描述】:

我的网站上有这个按钮,点击时会打开新页面,所以我试图为每个点击它并访问新页面的用户设置一个唯一的 cookie,如果有人尝试通过 url 直接访问新页面他们应该看到一个示例文本并自动重定向到按钮页面。我该怎么做?

<div class="button">
 <a href="/" target="_blank">CLICK HERE TO GET THIS..!</a>
</div>

【问题讨论】:

    标签: javascript php cookies session-cookies setcookie


    【解决方案1】:

    HTML:

    <div class="button">
         <a href="" onclick="what_i_want()" id="the_button" target="_blank">CLICK HERE TO 
         GET THIS..!</a>
    </div>
    

    JS:

    <script>
    function what_i_want()
    {
        var cookie_name=Math.floor(Math.random() * 1000000) + 1;  //random name for example;
        var cookie_value=" any value";  // << you also can get value from function >> what_i_want(par,par2,par,3);
        document.cookie = cookie_name +'='+ cookie_value;
        document.getElementById('the_button').href="TARGET_LOCATION";
    }
    </script>
    

    【讨论】:

    • 检查这个cookie的代码是什么,如果它是空的,如何显示一个div并将它们自动重定向到旧页面?
    • 也发送 cookie_name。通过 GET 方法。像这样: document.getElementById('the_button').href="TARGET_LOCATION?check_cookie="+cookie_name ;所以现在您可以从链接中获取该随机名称并使用该名称检查 cookie
    【解决方案2】:

    即使没有任何类型的数据库,您也可以使用网络浏览器内置的本地存储来保存项目。将应用程序设置为浏览器中的“新标签页”页面,只要您不清除缓存,待办事项就会保留在您的本地计算机上。

    以前,Cookie 是记住此类本地临时数据的唯一选择。本地存储具有显着更高的存储限制(5MB 与 4KB),并且不会随每个 HTTP 请求一起发送,因此它可能是客户端存储的更好选择。

    这里是localStorage 方法的概述。

    Method              Description
    
    setItem()       Add key and value to local storage
    getItem()       Retrieve a value by the key
    removeItem()    Remove an item by key
    clear()         Clear all storage
    

    试试看:

    localStorage.setItem('key', 'value');
    

    现在,如果您再次在控制台中测试 localStorage,您将找到新的键和值。

    Storage {key: "value", length: 1}
    

    更多关于如何使用localStorage的信息你可以找到Here

    【讨论】:

    • 你能给我看一下代码部分吗?
    猜你喜欢
    • 1970-01-01
    • 2014-05-16
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多