【问题标题】:How to get a cookie value for input field?如何获取输入字段的 cookie 值?
【发布时间】:2014-12-04 00:09:41
【问题描述】:

我有一个表单,并且我已经为输入字段设置了 cookie。当我转到inspect element 时,我可以在resources 中找到cookie。该代码是机密的,所以我无法显示我是如何设置我的 cookie 的。但我确信我可以在 resources->cookie 中找到选定的输入字段。

相同的表单出现在所有页面中。当我从一个页面重定向到另一个页面时,我选择的表单字段必须出现在所有页面中。

我使用下面的代码来获取 cookie 值

<script type="text/javascript">
    $(document).ready(function() {
        if(input1 = getCookie("input1 "))
            document.myform.input1.value = input1 ;
    });
</script>

但我收到Uncaught ReferenceError: getCookie is not defined 的错误

谁能提出这个错误的原因是什么?以及如何获取输入字段的获取 cookie 值?

【问题讨论】:

标签: php jquery cookies session-cookies setcookie


【解决方案1】:

通常你应该谷歌它如何设置cookie,不确定你是否将函数声明为getCookie之类的东西?

<script type="text/javascript">
    function setCookie(key, value) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    $(document).ready(function() {
        setCookie("input1",'1');
        alert(getCookie("input1"));
        document.myform.input1.value = getCookie("input1");
    });

</script>

这是小提琴http://jsfiddle.net/hr4mubsw/5/

更多信息请查看How do I set/unset cookie with jQuery?

希望对你有帮助:)

【讨论】:

  • 在函数getCookie(key)中你从哪里得到'key'
  • 其实关键是那个参数,无论创建的cookie名称应该是什么,我没有编辑,如果你看到编辑过的,你可能知道它是如何工作的。如果您尝试上面的代码,它将起作用。
猜你喜欢
  • 2014-07-21
  • 2022-06-29
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 2012-11-07
  • 2015-11-15
  • 1970-01-01
相关资源
最近更新 更多