使用表单输入设置Cookie [英] Setting cookies with form input

查看:54
本文介绍了使用表单输入设置Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用用户对Web表单的输入来创建用户名cookie.但是它不起作用,我也不知道为什么.你知道是什么问题吗?

I am trying to make a username cookie using the user's input to a web form. However it's not working and I don't know why. Do you know what the problem is?

<form>
    <input type="text" value="Enter Your Nickname" id="nameBox">
    <input type="button" value="Go!" id="submit" onClick="putCookie">
<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>

推荐答案

您可以检查以下代码,可能会对您有所帮助.

You can check below code, it might help you.

<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'));

While defined function name should be putCookies instead of storeValues and function call you can do this way: putCookie(document.getElementsByTagName('form'));

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

Inside the function definition cookie values can be get from the form as below: setCookie("userName", form[0].usrname.value);

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

Form element should have attribute : name='usrname'

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

It will surely set cookies for your username with form element.

这篇关于使用表单输入设置Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆