【问题标题】:Setting cookies with form input使用表单输入设置 cookie
【发布时间】:2015-08-05 20:20:46
【问题描述】:

我正在尝试使用用户对 Web 表单的输入来制作用户名 cookie。但是它不起作用,我不知道为什么。你知道问题出在哪里吗?

<form>
    <input type="text" value="Enter Your Nickname" id="nameBox">
    <input type="button" value="Go!" id="submit" onClick="setCookie();">
<form>


<script>
    var today = new Date();
    var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days

    function setCookie(name, value){
        document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
    }
    //this should set the UserName cookie to the proper value;
    function storeValues(form){
        setCookie("userName", form.submit.value);
        return true;
    }

</script>
</body>

【问题讨论】:

  • javascript代码中没有putCookie函数;看起来你叫它 setCookie
  • 修复它仍然不起作用
  • escape(value) 函数定义了吗?它返回了什么
  • 为什么你的scriptbody之外,headhtml里面?那是无效的标记。另外,您是否定义了formsubmit
  • 我已将脚本放入正文中。也许我没有正确检查 cookie。

标签: javascript forms cookies


【解决方案1】:

您可以查看下面的代码,它可能对您有所帮助。

<html>
<head>
    <script>
var today = new Date();
  var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days

  function setCookie(name, value)
  {
    document.cookie=name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
  }
function putCookie(form)
                //this should set the UserName cookie to the proper value;
  {
   setCookie("userName", form[0].usrname.value);

    return true;
  }

  </script>
</head>
<body>
<form>
 <input type="text" value="Enter Your Nickname" id="nameBox" name='usrname'>
 <input type="button" value="Go!" id="submit" onclick="putCookie(document.getElementsByTagName('form'));">
</form>
</body>


</html>

虽然定义的函数名称应该是 putCookies 而不是 storeValues 和函数调用,但您可以这样做: putCookie(document.getElementsByTagName('form'));

在函数定义中的cookie值可以从下面的表格中获取: setCookie("userName", form[0].usrname.value);

表单元素应该有属性:name='usrname'

它肯定会使用表单元素为您的用户名设置 cookie。

【讨论】:

  • 我刚刚修改了 html 元素的一些属性,所有其他的只是你的代码,解决它@user4485835
【解决方案2】:

将表格更改为:

<form onsubmit="storeValues(this)">
<input type="text" value="Enter Your Nickname" id="nameBox">
<input type="submit" value="Go!" id="submit">
<form>

和 storeValues(form) 函数:

{
   setCookie("userName", form.nameBox.value);
   return true;
}

【讨论】:

  • 你如何连接它们?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
相关资源
最近更新 更多