仅在提交表单时设置cookie

时间:2015-05-27 06:25:35

标签: jquery cookies page-refresh

我正在编写以下代码,仅在提交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;"
    });
});

2 个答案:

答案 0 :(得分:0)

提交后,您可能需要reset the form

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

因此,只有在重新提交时,才会设置Cookie。

答案 1 :(得分:-1)

<强>更新

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

来自https://github.com/carhartl/jquery-cookie的cookie的jquery插件

在脚本中添加两个脚本src =&#34; ...&#34;&gt;在html的标题中

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

希望这会有所帮助

相关问题