Javascript 使用表单输入设置 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30419929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting cookies with form input
提问by Hans.Gundlach
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?
我正在尝试使用用户对 Web 表单的输入来制作用户名 cookie。但是它不起作用,我不知道为什么。你知道问题是什么吗?
<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>
采纳答案by Ruchira Shree
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>
While defined function name should be putCookies instead of storeValues and function call you can do this way: putCookie(document.getElementsByTagName('form'));
虽然定义的函数名应该是 putCookies 而不是 storeValues 和函数调用你可以这样做: putCookie(document.getElementsByTagName('form'));
Inside the function definition cookie values can be get from the form as below: setCookie("userName", form[0].usrname.value);
在函数定义中,cookie 值可以从如下表单中获取: setCookie("userName", form[0].usrname.value);
Form element should have attribute : name='usrname'
表单元素应该有属性:name='usrname'
It will surely set cookies for your username with form element.
它肯定会使用表单元素为您的用户名设置 cookie。
回答by zorgan
Change the form to:
将表格更改为:
<form onsubmit="storeValues(this)">
<input type="text" value="Enter Your Nickname" id="nameBox">
<input type="submit" value="Go!" id="submit">
<form>
And storeValues(form) function to:
和 storeValues(form) 函数:
{
setCookie("userName", form.nameBox.value);
return true;
}

