【问题标题】:AJAX Request Data Is Not Present in the HttpContext objectHttpContext 对象中不存在 AJAX 请求数据
【发布时间】:2013-12-11 03:35:37
【问题描述】:

我正在尝试将一些数据发送到通用处理程序并使用 jQuery.ajax() 在响应中传递回该信息。出于某种原因,当我根据找到的另一个问题 (.NET Simple Form Submit via AJAX and JQUERY) 的答案发送数据时,context.Request 对象中没有任何内容。

这是我的 ajax 调用:

function retrieveStats(monster) {
    $.ajax({
        type: "POST",
        url: "MonsterRequests.ashx",
        data: { "monster": monster },
        contentType: "application/json; charset=utf-8",
        success: function (msg) {
            alert(msg.d);
        },
        error: function (jqXhr, status, errorThrown) {
            alert(errorThrown);
        }
    });
}

这是我的处理程序的代码:

public class MonsterRequests : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        string monsterName = context.Request["monster"];

        context.Response.ContentType = "text/plain";
        context.Response.Write("{\"d\":\"" + monsterName + "\"}");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

我可以通过访问 context.Request.InputStream 并通过 StreamReader 读取来提取信息,但我很好奇为什么我不能直接从请求中提取信息。

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: .net ajax httpcontext


    【解决方案1】:

    删除内容类型,因为您不发送 json。试试这个。

    var monster = "value";
        $.ajax({
            type: "POST",
            url: "MyHandler.ashx",
            data: { monster: monster },
            success: function(msg) {
                alert(msg.d);
            },
            error: function(jqXhr, status, errorThrown) {
                alert(errorThrown);
            }
        });
    

    【讨论】:

    • 删除内容类型使其在我发送数据时工作:{“monster”:monster}。我将其标记为答案。为什么它不像我拥有它那样被认为是 json。另外,我创建并发送了一个 JSON 对象(使用 $.parseJSON),但它仍然没有在请求中显示任何内容。
    • 默认 $.ajax 的 contentType 是 'application/x-www-form-urlencoded; charset=UTF-8' 请参阅链接:api.jquery.com/jQuery.ajax 当 HTTP 请求 Content-Type 值为“application/x-www-form-urlencoded”或“multipart/form-data”时,会填充 Form 属性。见链接:msdn.microsoft.com/en-us/library/…
    • 这就解释了。再次感谢。 :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多