【问题标题】:Setting cookie only when a form is submitted仅在提交表单时设置 cookie
【发布时间】:2015-08-09 01:55:12
【问题描述】:

我正在编写以下代码以仅在提交 id=AuditDetails 的表单时设置 cookie,但是以下代码在每次重新加载页面时设置 cookie。我错过了什么?

$(document).ready(function() { //Initial call to the functions.
    showdept();
    $("#AuditDetails").on("submit", function() {
        document.cookie = "active_audit=1;path=/;expires=1;"
    });
});

【问题讨论】:

  • 什么是 AuditDetails?请粘贴您的html
  • @MohamedBelal the form with id=AuditDetails is submitted,它是表单,不需要click 事件
  • 你能在这个提交部分检查 put alert 吗?如果警报出现 2 次,则意味着您的代码调用了 2 次。如果您的代码 2 次出现,那么您需要采取一些措施。我不认为这会出现 2 次。
  • Alex,这是我在问题中提到的一种形式。
  • @Maulik 检查我的答案

标签: jquery cookies page-refresh


【解决方案1】:

提交后您可能需要reset the form

onsubmit="this.submit(); this.reset(); return false;"

这样只有在重新提交时才会设置cookies。

【讨论】:

    【解决方案2】:

    更新

    How to detect/track postback in javascript?上有解决方案

    还有

    How can I check for IsPostBack in JavaScript?

    你需要在服务器端

      if(IsPostBack)
        {   
          ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var     isPostBack = true;", true);
        }
    

    在客户端

           if(isPostBack)  
                    {   // do your thing
    
                    }
            else
                {
                     $.cookie("name","value");
                }
    

    $.cookie 是 jquery 语法。可以从http://code.jquery.com/jquery-1.11.3.min.js下载jquery

    还有用于 cookie 的 jquery 插件来自这里 https://github.com/carhartl/jquery-cookie

    在脚本 src="..."> 中添加两个脚本在 html 的标题中

    基本上你是通过服务器端脚本编写javascript变量并在客户端读取它

    希望这会有所帮助

    【讨论】:

    • ClientScript.RegisterClientScriptBlock 是 asp.net。如果您使用的是java或php,那么我相信必须有相当于这个礼物
    • 我是 javascript 新手,这一切我都不知道。我只是不明白为什么每次我重新加载页面时它都会设置cookie,而它应该只在提交表单时设置cookie。你能帮我看看这里的代码吗?
    猜你喜欢
    • 2011-02-13
    • 2017-11-13
    • 1970-01-01
    • 2020-07-20
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    相关资源
    最近更新 更多