利用Ajax在web頁面關閉時清除session
========================Default.aspx.cs 開始===========================================
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request.QueryString["___command"])) { string cmd = Request.QueryString["___command"]; if (cmd == "ClearSession") Session.Remove("name");//清空Session } if (Session["name"] != null) this.Label1.Text = Session["name"].ToString(); } protected void Button1_Click(object sender, EventArgs e) { Session["name"] = "vvvvvvvvvvvvv"; if (Session["name"] != null) this.Label1.Text = Session["name"].ToString(); } } ========================Default.aspx.cs 結束===========================================
========================script.js 開始=========================================== function GetXmlHttpObject() { //建立XMLHttpRequest物件來發送和接收HTTP請求與響應 xmlHttpObj = null; try { // FireFox Opera 8.0+ Safari xmlHttpObj = new XMLHttpRequest(); if(xmlHttpObj.overrideMimeType) { xmlHttpObj.overrideMimeType('text/xml'); } } catch(e) { // IE try { xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttpObj; } function StateChanged() { if(___xmlHttp.readyState == 4) { if(___xmlHttp.status == 200) { } else { } } } var ___xmlHttp=null; function ClearSession() { if(___xmlHttp==null) ___xmlHttp = GetXmlHttpObject(); if(___xmlHttp == null) return false; var url = "?___command=ClearSession&___clientRandom=" + Math.random(); ___xmlHttp.open("GET", url, true); ___xmlHttp.onreadystatechange = StateChanged; ___xmlHttp.send(null); } window.onbeforeunload = function() { var n = window.event.screenX - window.screenLeft; var b = n > document.documentElement.scrollWidth-20; if(b && window.event.clientY < 0 || window.event.altKey) { ClearSession(); } } ========================script.js 結束===========================================