本文介绍了故障排除jQuery的AJAX调用ASP.NET中使用通用处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是故障排除一个jQuery AJAX调用ASP.NET的最好方法是什么?误差函数获取调用 - 我得到的警报弹出,上面写着错误,但我不知道为什么。当我连接到我的进程(W3wp.exe),并放置一个断点到我的通用处理器ProcessRequest方法背后的code,它并没有就此止步。因此,它甚至没有达到处理程序。为什么会是这样?

它也只能执行误差函数在我的搜索按钮(BtnUCSSearch)所有其他的点击。我没有一个选项,以preSS好吗像一个典型的JavaScript警告的错误弹出。它闪烁和消失。我试图把在返回false以prevent一整页回发,但这似乎并没有工作。

请求页面的JavaScript:

 的jQuery(#<%= BtnUCSSearch.ClientID%>中)。点击(函数(){

        urlToHandler ='/Accessioning/Ful​​lDataEntry/AddressSearch.ashx';
        //硬编码的输入值,现在
        jsonData ='{公司名称:XXX,PrimaryPhone:555-555-5555,邮政code:55555};
        jQuery.ajax({
            网址:urlToHandler,
            数据:jsonData,
            数据类型:JSON,
            键入:POST,
            的contentType:应用/ JSON的,
            成功:功能(数据){
                警报(data.UCSAddress);
            },
            错误:功能(数据,状态,jqXHR){
                警报(错误);
            }
        }); //结束jQuery.ajax

    });
 

响应页面AJAX调用$ C $后面(AddressSearch.ashx.vb)C:

 导入系统
进口的System.Web
进口System.Web.Services
进口System.Web.HttpContext

< WebService的([命名空间]:=​​htt​​p://tempuri.org/)> _
< WebServiceBinding(ConformsTo:= WsiProfiles.BasicProfile1_1)> _
公共类AddressSearch
    实现System.Web.IHttpHandler
    实现System.Web.SessionState.IReadOnlySessionState

    只读属性IsReusable()作为布尔实现IHttpHandler.IsReusable
        得到
            返回False
        最终获取
    高端物业

    公用Sub的ProcessRequest(BYVAL上下文的HttpContext)实现System.Web.IHttpHandler.ProcessRequest

        context.Response.ContentType =应用/ JSON

        昏暗的companyName作为字符串= DirectCast(HttpContext.Current.Request.Form(公司名称),字符串)
        昏暗primaryPhone作为字符串= DirectCast(HttpContext.Current.Request.Form(PrimaryPhone),字符串)
        昏暗邮政code的String = DirectCast(HttpContext.Current.Request.Form(邮政code),字符串)

        昏暗的JSON作为字符串={UCSAddress:XXXXXXXXX}
        context.Response.Write(JSON)

    结束小组

末级
 

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

2012/1/2 @下午12时49分更新

每两个答案,我做了一点点的故障排除。

好像我被检索查询字符串参数的方式并没有采用表格的工作。所以我现在使用的查询字符串代替。该页面仍然正确返回JSON对象。但至少我的查询字符串参数应该现在的工作。然而,在这项工作中,我明确叫我一般直接从浏览器处理程序 - 而不是通过我的jQuery.ajax电话。所以我知道的页面效果很好了。

<一个href="https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555-555-5555&Postal$c$c=55555" rel="nofollow">https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555-555-5555&Postal$c$c=55555

响应:

{responseProperty:XXXXXXXXX}

请注意,我没有这两种方法。即使这种方法杜阿尔特先生建议(JavaScriptSerializer)。他们都工作在同一个..只是一点点不同的架构。请注意,我不得不创建一个名为SimpleResponse的自定义类。

 公用Sub的ProcessRequest(BYVAL上下文的HttpContext)实现System.Web.IHttpHandler.ProcessRequest

    建筑#1无JavaScriptSerializer(作品)

    context.Response.ContentType =应用/ JSON
    昏暗的companyName作为字符串= DirectCast(HttpContext.Current.Request.QueryString(公司名称),字符串)
    昏暗primaryPhone作为字符串= DirectCast(HttpContext.Current.Request.QueryString(PrimaryPhone),字符串)
    昏暗邮政code的String = DirectCast(HttpContext.Current.Request.QueryString(邮政code),字符串)
    昏暗的JSON作为字符串={responseProperty:XXXXXXXXX}
    context.Response.Write(JSON)

    建筑#2 JavaScriptSerializer和SimpleResponse类(也适用)

    context.Response.ContentType =应用/ JSON
    昏暗的JSON作为JavaScriptSerializer =新JavaScriptSerializer()
    context.Response.Write(json.Serialize(新SimpleResponse()))
    HTTP://$c$creview.stackexchange.com/questions/3208/basic-simple-asp-net-jquery-json-example

结束小组

公共类SimpleResponse

    公共财产responseProperty()作为字符串
        得到
            返回_responseProperty
        最终获取
        设置(BYVAL值作为字符串)
            _responseProperty =价值
        结束设定
    高端物业
    私人_responseProperty作为字符串

    公共子新()
        _responseProperty =通过SimpleResponse类效应初探
    结束小组

末级
 

=====

我也试过包装我jsonData与JSON.stringify ..我仍然得到错误。最初,jQuery的甚至没有调用页上,因为处理程序的类名称有一个1结尾。当我创建的一般处理程序,它附加一个1,因为我已经有隐藏类的网页和code命名AddressSearch.aspx。因为我已经固定的。我不得不寻找AddressSearch1因为我不能直接双击它在Solution Explorer中编辑文件。

 &LT;%@ WebHandler LANGUAGE =VBcodeBehind =AddressSearch.ashx.vb级=UI.Web.AddressSearch1%&GT;
 

=====

现在它至少叫着我的code的后面,但它不能与数据我jsonData设置传递查询字符串参数(即我也stringify'ed)。它也仍然抛出的错误。

也把无功在我的JS变量前面。

我们越来越近了。

 的jQuery(#&LT;%= BtnUCSSearch.ClientID%&gt;中)。点击(函数(){

        VAR urlToHandler ='AddressSearch.ashx';
        // VAR urlToHandler =〜/ Accessioning / FullDataEntry / AddressSearch.ashx;
        // urlToHandler ='/Accessioning/Ful​​lDataEntry/AddressSearch.ashx';
        //硬编码的输入值,现在
        VAR jsonData ='{公司名称:XXX,PrimaryPhone:555-555-5555,邮政code:55555};
        // VAR jsonData = {[公司名称:XXX,PrimaryPhone:555-555-5555,邮政code:55555}];
        jQuery.ajax({
            网址:urlToHandler,
            数据:JSON.stringify(jsonData)
            数据类型:JSON,
            键入:POST,
            的contentType:应用/ JSON的,
            成功:功能(数据){
                //警报(来到这里);
                警报(data.responseProperty);
                的console.log(..回应:+数据);
                返回false;
            },
            错误:功能(数据,状态,jqXHR){
                警报(错误);
                //console.log("error:+ XMLHtt prequest.responseText);
                //console.log(..错误:+ data.responseText);
                的console.log(..错误);
                返回false;
            }
        });

    });
 

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

2012/1/2 @下午1时52

code段#1(GET请求):

 的jQuery(#&LT;%= BtnUCSSearch.ClientID%&gt;中)。点击(函数(){

        jQuery.get(AddressSearch.ashx,{公司名称:XXX,PrimaryPhone:555,邮政code:55555},功能(数据){
            警报(来到这里);
            //警报(数据加载:+ data.responseProperty);
            返回false;
        });

    });
 

通过申请页面调用页面(#1):

params:一个 http://screencast.com/t/oA0i48O5y7

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

回应:什么

通话直接通过浏览器(#1)页:<一href="https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555&Postal$c$c=55555" rel="nofollow">https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555&Postal$c$c=55555响应(页面输出),虽然控制台说什么:{responseProperty:通过SimpleResponse类效应初探}

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

code段#2(POST请求类型):

  VAR urlToHandler ='AddressSearch.ashx';
        VAR jsonData ='{公司名称:XXX,PrimaryPhone:555-555-5555,邮政code:55555};
        jQuery.ajax({
            网址:urlToHandler,
            数据:JSON.stringify(jsonData)
            数据类型:JSON,
            键入:POST,
            的contentType:应用/ JSON的,
            成功:功能(数据){
                如果(数据!= NULL){
                    警报(data.responseProperty);
                    的console.log(..回应:+数据);
                }
                返回false;
            },
            错误:功能(数据,状态,jqXHR){
                如果(数据!= NULL){
                    警报(错误:+ data.responseText);
                    的console.log(..错误:+ data.responseText);
                }
                警报(发生错误);
                返回false;
            }
        });
 

通过申请页面调用页面(#2):

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

岗位: http://screencast.com/t/VKZdgGuOl

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

通话直接通过浏览器(#2)页:<一href="https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555&Postal$c$c=55555" rel="nofollow">https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555&Postal$c$c=55555

响应(页输出),虽然控制台说什么:{responseProperty:通过SimpleResponse类效应初探}

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

2012/1/2 @ 2:48pm

最后code。请注意,即preventDefault()和这行code至prevent那个神秘的错误。两人都是遗留的问题:jQuery的(#表)递交(函数(){返回false;});。虽然与如preventDefault()调用,不需要其他线路。所以我评论一下。

  jQuery的(文件)。就绪(函数(){

        // jQuery的(#表)递交(函数(){返回false;});

        jQuery的(#&LT;%= TxtLastName.ClientID%&gt;中)。重点();
        。//jQuery("#<%=PnlUCSSearch.ClientID%&gt;中)隐藏();

        //启动未分配的集合站点地址搜索逻辑
        jQuery的(#&LT;%= DDLCollectionSite.ClientID%&gt;中)改变(函数(){。
            //警报(世界你好+ THIS.VALUE);
            如果(THIS.VALUE!=2){
                jQuery的(#&LT;%= PnlUCSSearch.ClientID%&gt;中)。隐藏();
                jQuery的(#&LT;%= DDLCollectionSite.ClientID%&gt;中)。重点();
            }
            其他 {
                jQuery的(#&LT;%= PnlUCSSearch.ClientID%&gt;中)。显示();
                jQuery的(#&LT;%= TxtUCSCompany.ClientID%&gt;中)。重点();
            }
        });

        jQuery的(#&LT;%= BtnUCSSearch.ClientID%&gt;中)。点击(函数(五){

// jQuery.get(AddressSearch.ashx,{公司名称:XXX,PrimaryPhone:555,邮政code:55555},功能(数据){
//警报(数据加载:+ data.responseProperty);
//返回false;
//});

            VAR urlToHandler ='AddressSearch.ashx';
            // VAR urlToHandler =〜/ Accessioning / FullDataEntry / AddressSearch.ashx;
            // urlToHandler ='/Accessioning/Ful​​lDataEntry/AddressSearch.ashx';
            //硬编码的输入值,现在
            VAR jsonData ='{公司名称:XXX,PrimaryPhone:555-555-5555,邮政code:55555};
            // VAR jsonData = {[公司名称:XXX,PrimaryPhone:555-555-5555,邮政code:55555}];
            jQuery.ajax({
                网址:urlToHandler,
                数据:JSON.stringify(jsonData)
                数据类型:JSON,
                键入:POST,
                的contentType:应用/ JSON的,
                成功:功能(数据){
                    如果(数据!= NULL){
                        警报(data.responseProperty);
                        的console.log(..回应:+数据);
                    }

                },
                错误:功能(数据,状态,jqXHR){
                    //如果(数据!= NULL){
                    //警报(错误:+ data.responseText);
                    //执行console.log(..错误:+ data.responseText);
                    //}
                    //警报(发生错误);

                }
            });
            即preventDefault();
        });

        // END未指定的回收点的地址搜索逻辑

    });
 

解决方案

如果主要的问题是,点击按钮控制使一个完整的回发,而不是你的处理程序的异步调用,您可以在任何地方添加这个code你的jQuery的单击事件处理中:

 的jQuery(#&LT;%= BtnUCSSearch.ClientID%&gt;中)。点击(函数(五){
    //现有code
    即preventDefault();
})
 

这工作,而不是返回false 停止浏览器的正常行为的按钮点击。

What is the best method to troubleshooting a jQuery AJAX call with ASP.NET? The error function is getting called--I get the alert to popup that says "Error", but I don't know why. When I attach to my process (w3wp.exe), and place a breakpoint into the code behind of my generic handler ProcessRequest method, it doesn't stop there. So it's not even reaching the handler. Why would that be?

It's also only executing the error function every other click on my search button (BtnUCSSearch). And I don't have an option to press okay on the Error popup like a typical JavaScript alert. It flickers and goes away. I tried putting in a return false to prevent a full page postback, but that didn't seem to work.

Requesting Page 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

    });

Response Page for AJAX call code behind (AddressSearch.ashx.vb):

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

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

1/2/2012 @ 12:49pm update

Per the two answers, I did a little bit more troubleshooting..

The way I was retrieving the query string parameters didn't seem to work by using Form. So I'm now using QueryString instead. The page was still returning the JSON object correctly. But at least my query string parameters should work now. However, in this exercise, I explicitly called my generic handler directly from the browser--not via my jQuery.ajax call. So I know the page works well now.

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

Response:

{ "responseProperty": "xxxxxxxxx" }

Note, I did both methods.. even the approach Mr. Duarte suggested (JavaScriptSerializer). They both work the same.. just a little bit different architecture. Notice I had to create a custom class called 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

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

I also tried wrapping my jsonData with JSON.stringify.. I'm still getting the error. Originally, the jQuery wasn't even calling the page because the class name on the handler had a "1" at the end. When I created the generic handler, it appended a "1" because I already had a page and code behind class named AddressSearch.aspx. I've since fixed that. I had to search for "AddressSearch1" because I couldn't directly edit the file by double clicking it in Solution Explorer.

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

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

Now it's at least calling my code behind, but it's not passing the query string parameters with the data I set in jsonData (that I also stringify'ed). It's also still throwing the errors.

Also put "var" in front of my JS variables.

We're getting closer.

    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;
            }
        });

    });

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

1/2/2012 @ 1:52pm

code snippet #1 (GET request):

    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;
        });

    });

calling page via request page (for #1):

params: http://screencast.com/t/oA0i48O5y7

headers: http://screencast.com/t/3khfRjI7

response: nothing

calling page via browser directly (for #1):https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555&PostalCode=55555response (page output) although console says nothing:{"responseProperty":"reponse via SimpleResponse class"}

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

code snippet #2 (POST request type):

        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;
            }
        });

calling page via request page (for #2):

headers: http://screencast.com/t/ostM7NKCxT

post: http://screencast.com/t/VKZdgGuOl

response: http://screencast.com/t/LP3R8OAm

calling page via browser directly (for #2):https://localhost/Accessioning/FullDataEntry/AddressSearch.ashx?CompanyName=xxx&PrimaryPhone=555&PostalCode=55555

response (page output) although console says nothing:{"responseProperty":"reponse via SimpleResponse class"}

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

1/2/2012 @2:48pm

Final code. Notice the e.preventDefault() and this line of code to prevent that mysterious error. Both were the remaining issues: jQuery("#form").submit(function() { return false; }); Although with the e.preventDefault() call, you don't need the other line. So I commented it out.

    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

    });
解决方案

If the main problem is that clicking the button control causes a full post back instead of an asynchronous call to your handler, you can add this code anywhere inside your jQuery click event handler:

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

This works rather than return false to stop the browser's normal behavior for the button click.

这篇关于故障排除jQuery的AJAX调用ASP.NET中使用通用处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:06