【问题标题】:jQuery Ajax Codebehind Post is "OK" but doesn't workjQuery Ajax Codebehind Post 是“OK”但不起作用
【发布时间】:2015-02-20 09:15:16
【问题描述】:

我尝试像这样通过 jQuery Ajax 在 ASP.NET 中调用一个函数:

var params = "{'name':" + "\"" + name + "\"}";
            $.ajax({
            type: "POST",
            url: "CreateTopic.aspx/CreateNewTopic",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {

            },
            failure: function (response) {
                alert("Failed to send : " + response);
            }
        });

我得到 [HTTP/1.1 500 内部服务器错误]。

如果我这样做:

        var params = "{'name':" + "\"" + name + "\"}";
        $.post("CreateTopic.aspx/CreateNewTopic", params);

我得到:[HTTP/1.1 200 OK]

但是我在这里放的调试点:

    [System.Web.Services.WebMethod]
    public static object CreateNewTopic(string name)
    {
        return PrivateTopic.createNewTopic(name, 1);
    }

未达到。

【问题讨论】:

  • 唯一的区别似乎是发送和请求的数据格式。我希望 Post 默认不会发送/请求 JSON。由于我现在只使用 WebAPI,因此我无法评论您需要对 ASPX 进行的更改。

标签: javascript jquery asp.net ajax json


【解决方案1】:

你不会相信,但答案是:

将目标框架更改为 .NET 4.0

此代码有效:

            var params = "{'name':" + "\"" + name + "\"}";
        $.ajax({
            type: "POST",
            url: "CreateTopic.aspx/CreateNewTopic",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
                alert("Topic " + name + " wurde erfolgreich gespeichert.");
            },
            failure: function (response) {
                alert("Failed to send : " + response);
            }
        });

【讨论】:

    【解决方案2】:

    你的数据属性应该是 {'name':" + "\"" + name + "\"} 不是"{'name':" + "\"" + name + "\"}",前者是对象,后者是作为查询参数无效的字符串。 更好的是,只需尝试以下行而不是使用“参数”变量。

            $.ajax({
            type: "POST",
            url: "CreateTopic.aspx/CreateNewTopic",
            data: {'name':" + "\"" + name + "\"},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
    
            },
            failure: function (response) {
                alert("Failed to send : " + response);
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多