为什么我无法从 AJAX 访问我的网络方法?

Why can I not access my webmethod from AJAX?

我正试图在我的 asp.net 页面中对网络方法进行 AJAX 调用,但我似乎无法传递数据。

这是我的AJAX电话

$.ajax({
    type: "GET",
    url: "EditView.aspx/GetAllKeywords",
    data: JSON.stringify({
        keywordIds: ['1', '2']
    }),
    contentType: "application/json; charset=utf-8",
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    },
    complete: function(jqXHR, status) {
        alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
    }
});

这是我的 WebMethod

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string GetAllKeywords(string[] keywordIds)
{
    return "it worked";
}

每次我 运行 它,我总是收到这个错误

"Invalid web service call, missing value for parameter: \u0027keywordIds\u0027."

这向我表明,它无法匹配我的 ajax 调用我的网络方法中的参数的数据。我做错了什么?

您是否在 web.config 上启用了网络服务的获取方法?

<configuration>
    <system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>

https://support.microsoft.com/en-us/kb/819267

我快速创建了一个示例应用程序,发现您应该使用 POST 而不是 GET。当我应用以下设置时,我能够点击 GetAllKeywords 方法并成功获得响应。

脚本

<script>
        $.ajax({
            type: "POST",
            url: "WebForm1.aspx/GetAllKeywords",
            data: JSON.stringify({
                keywordIds: ['1', '2']
            }),
            contentType: "application/json; charset=utf-8",
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
            },
            complete: function (jqXHR, status) {
                alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
            }
        });
    </script>

C#

使用 POST 而不是 GET

 [WebMethod(EnableSession = true)]
 [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
 public static string GetAllKeywords(string[] keywordIds)
 {
    return "it worked";
 }

调试

调试模式的快照,

首先创建数组变量,然后将该变量字符串化,如下所示:

$(document).ready(function () {
    var keys = new Array();
    keys[0] = "1";
    keys[1] = "2";
    keys[2] = "3";


    $.ajax({
    type: "POST",
    url: "EditView.aspx/GetAllKeywords",
    data: JSON.stringify({keywordIds:keys }),
    contentType: "application/json; charset=utf-8",
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " +   textStatus + "\n\nError: " + errorThrown);
    },
    complete: function(jqXHR, status) {
    alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
    }
 });
});