小编典典

使用ASP.NET中的通用处理程序对jQuery AJAX调用进行故障排除

ajax

使用ASP.NET解决jQuery AJAX调用的最佳方法是什么?错误函数被调用-
我收到弹出警告,提示“错误”,但我不知道为什么。当我附加到进程(w3wp.exe),并在我的通用处理程序ProcessRequest方法的后面的代码中放置一个断点时,它并没有就此停止。因此,它甚至没有到达处理程序。为什么会这样呢?

每单击我的搜索按钮(BtnUCSSearch),它也只会执行一次错误函数。而且我没有选择像典型的JavaScript警报一样在“错误”弹出窗口上按“确定”的选项。它闪烁并消失。我尝试将return
false设置为防止整个页面回发,但这似乎没有用。

请求页面JavaScript:

    jQuery("#<%=BtnUCSSearch.ClientID %>").click(function() {

        urlToHandler = '/Accessioning/FullDataEntry/AddressSearch.ashx';
        // hard coding input values for now
        jsonData = '{ "CompanyName":"xxx", "PrimaryPhone":"555-555-5555", "PostalCode":"55555" }';
        jQuery.ajax({
            url: urlToHandler,
            data: jsonData,
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json',
            success: function(data) {
                alert(data.UCSAddress);                 
            },
            error: function(data, status, jqXHR) {
                alert('Error');                 
            }
        }); // end jQuery.ajax

    });

(AddressSearch.ashx.vb)后面的AJAX调用代码的响应页:

Imports System
Imports System.Web
Imports System.Web.Services
Imports System.Web.HttpContext

<WebService([Namespace]:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AddressSearch
    Implements System.Web.IHttpHandler
    Implements System.Web.SessionState.IReadOnlySessionState

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

        context.Response.ContentType = "application/json"

        Dim companyName As String = DirectCast(HttpContext.Current.Request.Form("CompanyName"), String)
        Dim primaryPhone As String = DirectCast(HttpContext.Current.Request.Form("PrimaryPhone"), String)
        Dim postalCode As String = DirectCast(HttpContext.Current.Request.Form("PostalCode"), String)

        Dim json As String = "{ ""UCSAddress"": ""xxxxxxxxx"" }"
        context.Response.Write(json)

    End Sub

End Class

============================

2012年1月2日下午12:49更新

对于这两个答案,我进行了更多的故障排除。

我使用Form检索查询字符串参数的方法似乎不起作用。所以我现在改用QueryString。该页面仍在正确返回JSON对象。但是至少我的查询字符串参数现在应该可以工作。但是,在本练习中,我直接从浏览器中显式调用了通用处理程序,而不是通过jQuery.ajax调用。所以我知道页面现在运行良好。

https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName =
xxx&PrimaryPhone = 555-555-5555&PostalCode =
55555

响应:

{“ responseProperty”:“ xxxxxxxxx”}

请注意,我完成了这两种方法。甚至是Duarte先生建议的方法(JavaScriptSerializer)。它们的工作原理是一样的。只是体系结构略有不同。注意,我必须创建一个名为SimpleResponse的自定义类。

Public Sub ProcessRequest(ByVal context As HttpContext) Implements System.Web.IHttpHandler.ProcessRequest

    ' architecture #1 without JavaScriptSerializer (works)

    context.Response.ContentType = "application/json"
    Dim companyName As String = DirectCast(HttpContext.Current.Request.QueryString("CompanyName"), String)
    Dim primaryPhone As String = DirectCast(HttpContext.Current.Request.QueryString("PrimaryPhone"), String)
    Dim postalCode As String = DirectCast(HttpContext.Current.Request.QueryString("PostalCode"), String)
    Dim json As String = "{ ""responseProperty"": ""xxxxxxxxx"" }"
    context.Response.Write(json)

    ' architecture #2 with JavaScriptSerializer and SimpleResponse class (also works)

    'context.Response.ContentType = "application/json"
    'Dim json As JavaScriptSerializer = New JavaScriptSerializer()
    'context.Response.Write(json.Serialize(New SimpleResponse()))
    'http://codereview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example

End Sub

Public Class SimpleResponse

    Public Property responseProperty() As String
        Get
            Return _responseProperty
        End Get
        Set(ByVal value As String)
            _responseProperty = value
        End Set
    End Property
    Private _responseProperty As String

    Public Sub New()
        _responseProperty = "reponse via SimpleResponse class"
    End Sub

End Class

================

我还尝试用JSON.stringify包装我的jsonData。我仍然收到错误。最初,jQuery甚至没有调用页面,因为处理程序上的类名末尾带有“
1”。创建通用处理程序时,它会附加一个“
1”,因为我已经在名为AddressSearch.aspx的类后面有一个页面和代码。此后,我已修复该问题。我必须搜索“
AddressSearch1”,因为无法通过在解决方案资源管理器中双击文件来直接对其进行编辑。

<%@ WebHandler Language="VB" CodeBehind="AddressSearch.ashx.vb" Class="UI.Web.AddressSearch1" %>

================

现在,至少要在后面调用我的代码,但是没有将查询字符串参数与我在jsonData中设置的数据(我也进行过字符串化处理)一起传递。它还仍然会引发错误。

还要在我的JS变量前面加上“ var”。

我们越来越近了。

    jQuery("#<%=BtnUCSSearch.ClientID %>").click(function() {

        var urlToHandler = 'AddressSearch.ashx';
        //var urlToHandler = '~/Accessioning/FullDataEntry/AddressSearch.ashx';
        //urlToHandler = '/Accessioning/FullDataEntry/AddressSearch.ashx';
        // hard coding input values for now
        var jsonData = '{ CompanyName:"xxx", PrimaryPhone:"555-555-5555", PostalCode:"55555" }';
        //var jsonData = [{ CompanyName: "xxx", PrimaryPhone: "555-555-5555", PostalCode: "55555"}];
        jQuery.ajax({
            url: urlToHandler,
            data: JSON.stringify(jsonData),
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json',
            success: function(data) {
                //alert("got here");
                alert(data.responseProperty);
                console.log(" .. response :" + data);
                return false;
            },
            error: function(data, status, jqXHR) {
                alert('Error');
                //console.log("error :" + XMLHttpRequest.responseText);
                //console.log(" .. error :" + data.responseText);
                console.log(" .. error");
                return false;
            }
        });

    });

=========================

2012年1月2日下午1:52

代码段#1(获取请求):

    jQuery("#<%=BtnUCSSearch.ClientID %>").click(function() {

        jQuery.get("AddressSearch.ashx", { CompanyName: "xxx", PrimaryPhone: "555", PostalCode: "55555" }, function(data) {
            alert("got here");
            //alert("Data Loaded: " + data.responseProperty);
            return false;
        });

    });

通过请求页面调用页面(针对#1):

参数:http :
//screencast.com/t/oA0i48O5y7

标头:http//screencast.com/t/3khfRjI7

回应:没事

通过浏览器直接调用页面(对于#1):
https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName =
xxx&PrimaryPhone = 555&PostalCode =
55555

响应(页面输出),尽管控制台未显示任何内容:{“ responseProperty”:“通过SimpleResponse类“}

=====================

代码段2(POST请求类型):

        var urlToHandler = 'AddressSearch.ashx';
        var jsonData = '{ CompanyName:"xxx", PrimaryPhone:"555-555-5555", PostalCode:"55555" }';
        jQuery.ajax({
            url: urlToHandler,
            data: JSON.stringify(jsonData),
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json',
            success: function(data) {
                if (data != null) {
                    alert(data.responseProperty);
                    console.log(" .. response :" + data);
                }
                return false;
            },
            error: function(data, status, jqXHR) {
                if (data != null) {
                    alert("Error: " + data.responseText);
                    console.log(" .. error :" + data.responseText);
                }
                alert("error occurred");
                return false;
            }
        });

通过请求页面调用页面(针对#2):

标头:http//screencast.com/t/ostM7NKCxT

帖子:http :
//screencast.com/t/VKZdgGuOl

响应:http :
//screencast.com/t/LP3R8OAm

通过浏览器直接调用页面(针对#2):
https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName =
xxx&PrimaryPhone = 555&PostalCode =
55555

响应(页面输出),尽管控制台什么也没说:{“ responseProperty”:“通过SimpleResponse类进行响应”}

===========================

2012年1月2日下午2:48

最终代码。请注意e.preventDefault()和这一行代码,以防止该神秘错误。剩下的两个都是:jQuery(“#form”)。submit(function(){return
false;}); 尽管使用e.preventDefault()调用,您不需要另一行。所以我把它注释掉了。

    jQuery(document).ready(function() {

        //jQuery("#form").submit(function() { return false; });

        jQuery("#<%=TxtLastName.ClientID %>").focus();
        //jQuery("#<%=PnlUCSSearch.ClientID %>").hide();

        // START unassigned collection site address search logic
        jQuery("#<%=DDLCollectionSite.ClientID %>").change(function() {
            //alert("hello world: " + this.value);
            if (this.value != "2") {
                jQuery("#<%=PnlUCSSearch.ClientID %>").hide();
                jQuery("#<%=DDLCollectionSite.ClientID %>").focus();
            }
            else {
                jQuery("#<%=PnlUCSSearch.ClientID %>").show();
                jQuery("#<%=TxtUCSCompany.ClientID %>").focus();
            }
        });

        jQuery("#<%=BtnUCSSearch.ClientID %>").click(function(e) {

//          jQuery.get("AddressSearch.ashx", { CompanyName: "xxx", PrimaryPhone: "555", PostalCode: "55555" }, function(data) {
//              alert("Data Loaded: " + data.responseProperty);
//              return false;
//          });

            var urlToHandler = 'AddressSearch.ashx';
            //var urlToHandler = '~/Accessioning/FullDataEntry/AddressSearch.ashx';
            //urlToHandler = '/Accessioning/FullDataEntry/AddressSearch.ashx';
            // hard coding input values for now
            var jsonData = '{ CompanyName:"xxx", PrimaryPhone:"555-555-5555", PostalCode:"55555" }';
            //var jsonData = [{ CompanyName: "xxx", PrimaryPhone: "555-555-5555", PostalCode: "55555"}];
            jQuery.ajax({
                url: urlToHandler,
                data: JSON.stringify(jsonData),
                dataType: 'json',
                type: 'POST',
                contentType: 'application/json',
                success: function(data) {
                    if (data != null) {
                        alert(data.responseProperty);
                        console.log(" .. response :" + data);
                    }

                },
                error: function(data, status, jqXHR) {
                    //if (data != null) {
                    //    alert("Error: " + data.responseText);
                    //    console.log(" .. error :" + data.responseText);
                    //}
                    //alert("error occurred");

                }
            });
            e.preventDefault(); 
        });

        // END unassigned collection site address search logic

    });

阅读 162

收藏
2020-07-26

共1个答案

小编典典

我尝试将return false设置为防止整个页面回发,但这似乎没有用。

如果主要问题是单击按钮控件导致完整回发,而不是异步调用处理程序,则可以将此代码添加到jQuery click事件处理程序中的任何位置:

jQuery("#<%=BtnUCSSearch.ClientID %>").click(function(e) {
    // Existing code
    e.preventDefault();
})

这是有效的方法,而不是return false停止按钮单击时浏览器的正常行为。

2020-07-26