jquery ajax имеет проблему с получением возвращаемого значения от обработчика ashx

Привет,

Независимо от того, что я делаю, я не могу заставить свой код jquery ajax получить ответ, отличный от нуля, со страницы обработчика ashx.

Вот моя страница хмт:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>:: ashx tester ::</title>
    <link rel="stylesheet" href="js/jqueryui/1.8.6/themes/sunny/jquery-ui.css"
        type="text/css" media="all" />
    <script type="text/javascript" src="js/jquery/1.4.3/jquery.min.js"></script>
    <script type="text/javascript" src="js/jqueryui/1.8.6/jquery-ui.min.js"></script>
    <script type="text/javascript" src="js/json2/0.0.0/json2.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btnSubmit').click(
                function () {
                    DoIt();
                }
            );
        });

        function DoIt() {
            $('#btnSubmit').hide();
            $.ajax({
                type: "POST",                
                url: "http://localhost:49424/Handler1.ashx",
                data: {
                    firstName: 'Bob',
                    lastName: 'Mahoney'
                },
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert('success: ' + response);
                    $('#btnSubmit').show();
                },
                error: function (response) {
                    alert('error: ' + response);
                    $('#btnSubmit').show();
                }
            });
        }
    </script>
</head>
<body>
    <input id="btnSubmit" type="button" value="Submit" />
</body>
</html>

А вот моя страница ashx:

Imports System.Web
Imports System.Web.Services
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data
Imports System.Configuration.ConfigurationManager
Imports System.Web.Services.Protocols
Imports System.Web.Script.Serialization

Public Class Handler1
    Implements System.Web.IHttpHandler

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim j As New System.Web.Script.Serialization.JavaScriptSerializer
        Dim s As String

        s = j.Serialize(Now)
        context.Response.ContentType = "application/json"
        context.Response.Write(s)

    End Sub

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

End Class

Любые подсказки?

Спасибо!

Дэйв


person Dave    schedule 06.04.2011    source источник


Ответы (3)


Попробуйте URL: "/Handler1.ashx",

вместо

 url: "http://localhost:49424/Handler1.ashx",
person simplyaarti    schedule 06.04.2011
comment
Хорошо... вот странная часть. Это сработало, но не совсем. Мне нужно, чтобы страница могла удаленно вызывать мой обработчик ashx. Но для проверки я скопировал свою страницу в свой проект и внес предложенные вами изменения. Это сработало! Итак, я снова попробовал удаленную страницу, но на этот раз в IE... Я тестировал удаленную страницу с помощью Chrome. Оказывается, ajax-вызов удаленной страницы работает в IE, но не работает в Chrome или Firefox! - person Dave; 06.04.2011

Я использую только текстовый тип данных с обработчиками

      var webServiceURL = 'http://localhost:12400/Handler1.ashx';
        var data = "Key:Value";

        alert(data);

        $("input[id='btnSubmitLead']").click(function () {
            $.ajax({
                type: "POST",
                url: webServiceURL,
                data: data,
                dataType: "text",
                success: function (results) {
                    alert("Your information has been sent to the dealer, thank you");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus +"-"+ errorThrown);
                    alert("Your information has not been sent");
                }
            });
        });

Итак, я получаю информацию обработчику во всех браузерах, но не получаю надлежащего подтверждения, так как это всегда ошибка. Я использую html-страницу для отправки вызова ajax. Я также удалил:

         context.Response.ContentType = "application/json"

от моего обработчика, который увеличил работу на стороне сервера, но также вызов сервера был в порядке ... его возврат назад вызвал у меня проблемы.

person Clarence    schedule 22.09.2013

Этот упрощенный код работает для меня..

    $.ajax({
        type: "POST",
        url: "AddProviderToCall.ashx",
        data: {ProviderID: strProviderID, PhyUserID: PhyUserID },
        success: function (response) {
            alert('success: ' + response);
        },
    });

В моем обработчике С#..

{
    context.Response.ContentType = "text/plain";
    context.Response.Write(result);
}
person Ichi San    schedule 16.09.2014