【问题标题】:How can I clear asp.net session value in OnUnload event in javascript如何在 JavaScript 的 OnUnload 事件中清除 asp.net 会话值
【发布时间】:2013-07-21 11:59:30
【问题描述】:

我想在浏览器关闭时清除 ASP.NET 会话值。我在html 页面中定义了 onunload 函数,但我不知道如何在这个 Javascript 方法中清除会话值?

<body onunload="myUnloadFunction()">


<script>
function myUnloadFunction()
{
  // Needs asp.net session code here
}
</script>

请让我知道是否还有其他更好的方式。

【问题讨论】:

  • @KhanhTO - 他无法清除 JavaScript 中的会话值,但他可以在他的 JavaScript 代码中回调服务器,如我的回答所示。

标签: c# javascript html asp.net


【解决方案1】:

试试这个:

代码隐藏:

[WebMethod]
public static void ClearYourSessionValue()
{
    // This will leave the key in the Session cache, but clear the value
    Session["YourKey"] = null;

    // This will remove both the key and value from the Session cache
    Session.Remove("YourKey");
}

JavaScript:

$.ajax({
    type: "POST",
    url: "PageName.aspx/ClearYourSessionValue",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
         // Do something interesting here.
    }
});

如果您想了解有关ASP.NET AJAX Page Methods 以及如何通过AJAX 调用它们的更多信息,请阅读Using jQuery to directly call ASP.NET AJAX page methods

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-10
    • 1970-01-01
    • 2012-01-30
    • 2014-09-15
    相关资源
    最近更新 更多