jquery - 无法在页面卸载事件中调用 post 到 asp.net 页面

标签 jquery asp.net ajax server-side

我正在尝试在使用框架集的旧应用程序中工作。我正在尝试从页面卸载事件触发服务器端代码。下面是一些演示该问题的示例代码。

默认.aspx:

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="SimpleTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<frameset rows="20%,80%">
    <frame name="Frame2" src="Frame2.aspx">
        <frameset>
            <frame name="Frame1" src="Frame1.aspx">
    </frameset>
</frameset>
</html>

Frame2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Frame2.aspx.cs" Inherits="SimpleTest.Frame2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <asp:Button ID="btnSecond" runat="server" Text="Button Second" onclick="btnSecond_Click" /> 
    </div>
</form>
<script type="text/javascript">
    if ('onbeforeunload' in window) {
        window.onbeforeunload = (function () { clearSessionData(); });
    } else {
        if ('onunload' in window) {
            window.onunload = (function () { clearSessionData(); });
        }
    }

    function clearSessionData() {
        alert("clearSessionData fired!");
        $.ajax({
            type: "POST",
            url: "Frame2.aspx/someFunction",
            success: function () { alert("SUCCESS"); },
            error: function () { alert("ERROR"); }
        });
    }
</script>
</body>
</html>

Frame2.aspx.cs:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SimpleTest
{
    public partial class Frame2 : System.Web.UI.Page
    {
        protected void btnSecond_Click(object sender, EventArgs e)
        {
            int test = 1;
            test++;
        }

        protected void someFunction()
        {
            int test = 1;
            test++;
        }
    }
}

在本例中,我没有包含 Frame1.aspx 的代码,因为该页面是空的。

如果我运行此测试代码,则会出现“clearSessionData已触发!”的警报。运行,并弹出警告框。但是,下一行不会触发服务器函数“someFunction”。

我也尝试过使用 $.post() 而不是 $.ajax(),但是也没有成功。有人对此有经验吗?尝试使用 jQuery 从框架集中触发服务器端代码是否存在问题?您将如何使用 jQuery 或任何其他方法来完成此任务?我尝试了几种选择,但是似乎没有什么可以触发服务器端代码。

如有任何建议,我们将不胜感激。

谢谢。

添加评论:

作为旁注,如果我有一个简单的页面,没有框架,我可以将代码放入按钮的服务器端单击事件中,然后创建一个 Javascript 函数,该函数使用 jQuery 的“触发”方法来调用按钮的服务器 -侧面点击代码没有任何问题。请参阅此示例代码:

<body>
<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
<script type="text/javascript">
    if ('onbeforeunload' in window) {
        window.onbeforeunload = (function () { clearSessionData(); });
    } else {
        if ('onunload' in window) {
            window.onunload = (function () { clearSessionData(); });
        }
    }

    function clearSessionData() {
        $("#Button1").trigger("click");
    }
</script>

这工作得很好,当浏览器关闭时会触发点击事件代码(以及触发卸载的其他事件)。但是,无论出于何种原因,使用框架都会打破这一切。

最佳答案

您需要将 someFunction(在服务器上)转换为页面方法。可以通过 AJAX 调用从客户端代码调用页面方法。

这里有一篇文章对此进行了解释:http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

基本上,您可以使用 WebMethod 和 ScriptMethod 属性来装饰您的方法。另外,公开一下:

[WebMethod, ScriptMethod]    
public static void someFunction()
{
    int test = 1;
    test++;
}

这些将需要使用 System.Web.Services 和 System.Web.Script.Services 的语句。

更新:我刚刚看到您更新的问题,说您正在使用 .NET 2.0。如果您无法使用页面方法,这里有一个解决方法。首先,创建一个通用 HttpHandler。我将我的KillSession.ashx 命名为KillSession.ashx。请注意,您还必须实现标记接口(interface) IRequiresSessionState 才能访问 HttpSession。

KillSession.ashx.cs:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;

namespace TestFrames
{
    /// <summary>
    /// Summary description for KillSession
    /// </summary>
    public class KillSession : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.Session != null)
            {
                context.Session.Clear();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

在 Default.aspx(框架容器)中添加一个名为killSession 的函数。注意它调用 KillSession.ashx:

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Default.aspx.cs" Inherits="SimpleTest._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
        function killSession() {
            console.log("Killing Session");
            $.ajax({
                type: "POST",
                url: "KillSession.ashx",
                success: function () { alert("SUCCESS"); },
                error: function () { alert("ERROR"); }
            });
        }
    </script>
</head>
<frameset rows="20%,80%">
    <frame name="Frame2" src="Frame2.aspx">
        <frameset>
            <frame name="Frame1" src="Frame1.aspx">
    </frameset>
</frameset>
</html>

然后从您的框架页面(例如 Frames2.aspx):

<script type="text/javascript">
    if ('onbeforeunload' in window) {
        window.onbeforeunload = (function () { clearSessionData(); });
    } else {
        if ('onunload' in window) {
            window.onunload = (function () { clearSessionData(); });
        }
    }

    function clearSessionData() {
        alert("clearSessionData fired!");
        if (typeof window.top.killSession === "function") {
            window.top.killSession();
        }
    }
</script>

每当框架内发生卸载事件时,这将调用顶级框架 (Default.aspx) KillSession 函数。

关于jquery - 无法在页面卸载事件中调用 post 到 asp.net 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22916782/

相关文章:

javascript - jQuery,remove 并没有删除子元素,只是删除了父元素

javascript - 在 html 元素中内联按键以捕获输入

javascript - 通过 Ajax 将数据从 Javascript 发送到 JSON、PHP

javascript - 使用 jQuery 设置元素的 onclick 属性时遇到问题

javascript - 如何使用其 ID 在 jquery/javascript 中选择动态生成的表单元素?

c# - 为什么应用程序无一异常(exception)地默默死去?

c# - asp.net GridView 批量更新所有单元格

c# - 不传输文件的FileUpload

javascript - ajax成功访问类函数

Javascript 修改 URL 并分配 URL,而不使用源作为父级