【问题标题】:asp.net ashx handler: can't receive responseasp.net ashx 处理程序:无法接收响应
【发布时间】:2015-04-29 03:25:02
【问题描述】:

大家好,感谢您的宝贵时间。 这是我的javascript:

$('.sender').click(function (e) {       
    $.ajax({
        type: "POST",
        url: "fHandler.ashx",
        data: { firstName: 'stack', lastName: 'overflow' },
        // DO NOT SET CONTENT TYPE to json
        // contentType: "application/json; charset=utf-8", 
        // DataType needs to stay, otherwise the response object
        // will be treated as a single string
        dataType: "json",
        success: function (response) {
            alert('success');
        },
        error: function (response) {
            alert('error: ' + response);
            console.log('err: '+response);
        }
    });                    
});

这是我的 .ashx 处理程序中的代码:

public void ProcessRequest(HttpContext context)
{
    context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
    context.Response.ContentType = "text/plain";
    string json = new StreamReader(context.Request.InputStream).ReadToEnd();
    context.Response.Write(json);
}

public bool IsReusable
{
    get
    {
        return false;
    }
}

当点击事件工作时,我的Ajaxrequest 似乎没有得到任何响应,因为成功时没有弹出警报。我已经使用浏览器的网络控制台进行了调试,它返回了预期的响应,但它似乎没有达到JavaScript 代码中的成功函数。欢迎任何见解或建议。谢谢。

【问题讨论】:

  • 单个字符串不是有效的 json。添加错误处理程序会有所帮助。还要检查浏览器控制台的网络选项卡中的请求以获取线索
  • 我已经编辑了我的帖子,但仍然无法弹出该警报。然而,这些帖子确实会发回 200 个响应状态。
  • 更改 dataType: "text" 后让它工作

标签: javascript jquery asp.net ajax ashx


【解决方案1】:

如果您仍然对答案感兴趣,请在提出请求之前尝试此操作

var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);

并将您的 AJAX 请求更改为

$.ajax({
    type: "POST",
    url: "fHandler.ashx",
    data: jsonData,
    dataType: 'json',
    contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
    // do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
    console.log("request error");
    console.log(textStatus);
    console.log(errorThrown);
});

说明

您正在尝试发送纯 data 对象。您必须使用 JSON.stringify(object) 将其转换为 Json 字符串。

更改数据类型并不是真正的解决方案,而是一种解决方法。

补充说明

另外,我认为你应该使用.done().fail()See here 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2011-11-09
    • 2011-04-11
    相关资源
    最近更新 更多