如何在javascript中清除OnUnload事件中的asp.net会话值

How can I clear asp.net session value in OnUnload event in javascript

本文关键字:asp net 会话 事件 OnUnload javascript 清除      更新时间:2023-09-26

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

<body onunload="myUnloadFunction()">

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

请告诉我还有其他更好的方法吗。

试试这个:

代码背后:

[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