【发布时间】:2014-03-15 20:07:27
【问题描述】:
我正在尝试使用 JS cookie 在页面加载时自动提交我的表单,以下是我的代码,但它不起作用。任何帮助都是不言而喻的。谢谢你。 我对与设置和获取 cookie 相关的代码表示怀疑。
<html>
<head>
<script>
window.onload = function()
{
if(window.location == "hello.html")
{
alert("location match");
var x = getCookie("crmodtaskform");
alert("cookie retrieved");
alert("x:" + x);
if(x == "")
{
setCookie("crmodtaskform",yes);
alert("cookie set");
document.checkform.submit();
}
else
{
alert("cookie is already set and form already submiteed once");
}
}
}
function setCookie(cname,cvalue)
{
document.cookie = cname + "=" + cvalue + ";";
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
</script>
</head>
<body>
<form name="checkform" method="POST">
First Name: <input type="text" id="fn"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
【问题讨论】:
-
为什么需要 cookie 来在页面加载时提交表单?!
-
这段代码只是示例。我的目的不同。我想在加载页面上提交一次表单。请告诉我为什么我的 cookie 不起作用?
-
看起来你要做的就是只提交一次表单,下次再次加载文档并提交相同的表单时,你需要阻止提交,因为表单是已经提交了,是吗?
-
是的。在我的实际应用程序中,我只能访问标题,而在正文中有级联下拉列表。为了使下拉级联,我需要在页面加载时提交一次表单。
标签: javascript html cookies