简体   繁体   English

JavaScript cookie无法在表单提交中使用

[英]Javascript cookie not working on form submit

I have a form like this: 我有这样的形式:

<form id="loginCompact" action="https://externalsite..." name="sportsbook" method="post" onsubmit="createCookie('BRLOG', document.sportsbook.username.value, 1)">
    <input type="text" name="username" class="loginUsername" />
    ...other fields...
</form>

And this is the Javascript function that's called: 这就是所谓的Javascript函数:

<script type="text/javascript">
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/; domain='mydomain.com'";
}
</script>

However, the cookie is not getting set when the form is submitted. 但是,提交表单时未设置cookie。 It was working fine when attached to the onclick handler of the button, but not on onsubmit . 附加到按钮的onclick处理程序时,它工作正常,但onsubmit不能。 Any ideas? 有任何想法吗?

Check to make sure onsubmit is spelled correctly (maybe it's onSubmit?). 检查并确保onsubmit的拼写正确(也许是onSubmit?)。

Simplify by putting an alert in instead of a call to your function 通过放置警报而不是调用函数来简化

onsubmit="alert('test')"

Put an alert at the top of your function to see if it's getting called and the cookie isn't being set for some more complicated reason. 在函数顶部放置一个警报,以查看是否正在调用它,以及由于某些更复杂的原因而未设置cookie。

If it is getting called, check to make sure that all of the variables your rely on are correct, using alerts, or (better), something like firebug. 如果它被调用,请使用警报或(更好)(如萤火虫)检查以确保您依赖的所有变量都是正确的。

我发现了这一点-我需要在域名前加句号,并删除引号:

domain=.mydomain.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM