asp.net ashx处理程序:can't接收响应

asp.net ashx handler: can't receive response

本文关键字:响应 can ashx net 处理 程序 asp      更新时间:2024-06-26

大家好,感谢您抽出时间。这是我的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;
    }
}

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

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

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字符串。

更改dataType并不是真正的解决方案,而是一种变通方法。

附加说明

此外,我认为您应该使用.done().fail()。请参阅此处了解更多详细信息。