直接从AJAX调用Code-Behind函数,无需加载页面

时间:2015-06-04 13:48:02

标签: javascript jquery asp.net ajax dotnetnuke

我试图直接调用函数后面的代码。目前,我能够从我的ajax.aspx.vb的PageLoad事件中调用该函数,并通过ajax.aspx <%= m_result %>上的变量传递响应。这很好用。但是,我不想通过PageLoad事件,而是直接定位函数而不必将数据放入<%= m_result %>。有可能吗?

我正在使用DotNetNuke,其中所有功能都来自ascx控件。 所以,在我的ascx控件中,我将ajax视为:

<script type = "text/javascript">
    function JSFunction() {
        var xx = 1;
            $.ajax({
                type: "POST",
                url: "/top3/DesktopModules/top3all/ajax.aspx/GetTestData",
                data: { 'sPageIndex': xx},
            }).done(function (response) {
             OnSuccessTest(response);
            });
    }
    function OnSuccessTest(response) {
        document.getElementById("<%= lblTest.ClientID%>").innerHTML = response;
}
</script>

在我的ajax.aspx.vb中:

 Protected m_result As String = ""

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim sModuleIDReferrer As String
        If Not HttpContext.Current.Request.UrlReferrer Is Nothing Then
            strUrl = HttpContext.Current.Request.UrlReferrer.ToString

            Dim sPageIndex As Integer
            If Integer.TryParse(Request("sPageIndex"), sPageIndex) Then

                GetTestData(sPageIndex)
            End If
          End If
    End Sub

 <System.Web.Services.WebMethod()> _
 Public Shared Function GetTestData(ByVal name As Integer) As String
        m_result = "some test"
        Return m_result
    End Function

在我的ajax.aspx中:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ajax.aspx.vb" Inherits="Christoc.Modules.top3all.ajax" %>
<%= m_result %>

2 个答案:

答案 0 :(得分:0)

相信这就是你所需要的 -

在您的aspx页面中,添加一个ScriptManager控件,并将其EnablePageMethods属性设置为True

<asp:ScriptManager runat="server" ID="MySM" runat="server" EnablePageMethods="True" />

在代码隐藏中修改方法声明,如下所示:

<System.Web.Services.WebMethod()> _
 Public Shared Function GetTestData(ByVal name As Integer) As String
        m_result = "some test"
        Return m_result
 End Function

答案 1 :(得分:0)

在@David上添加<System.Web.Services.WebMethod()>之后,您可以尝试更改JS以使用PageMethods check this answer,在那里您可以找到所需的一切。

希望这个帮助

相关问题