为什么我不能从AJAX访问我的webmethod?

时间:2015-07-28 05:25:05

标签: jquery asp.net ajax webmethod

我试图在我的asp.net页面中对web方法进行AJAX调用,而我似乎无法传递数据。 这是我的AJAX电话 $就({     输入:" GET",     url:" EditView.aspx / GetAllKeywords",     data:JSON.stringify({         keywordIds:[' 1',' 2']     }),     contentType:" application / json;字符集= UTF-8&#34 ;,     error:function(XMLHttpRequest,textStatus,errorThrown){         警告("请求:" + XMLHttpRequest.toString()+" \ n \ n状态:" + textStatus +" \ n \ n错误:" + errorThrown );     },     完成:function(jqXHR,status){         警报("完成:" +状态+" \ n \ n响应:" + jqXHR.responseText);     } }); 这是我的WebMethod [WebMethod(EnableSession = true)] [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)] public static string GetAllKeywords(string [] keywordIds) {     返回"它工作&#34 ;; } 每次我运行它,我都会遇到这个错误 "无效的Web服务调用,缺少参数值:\ u0027keywordIds \ u0027。" 这对我来说,它无法将我的ajax调用中的数据与我的webmethod中的参数进行匹配。我究竟做错了什么?

3 个答案:

答案 0 :(得分:2)

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

<强> SCRIPT

<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";
 }

<强> DEBUG

来自调试模式的快照,

enter image description here

答案 1 :(得分:0)

您是否在web.config上启用了web服务的get方法?

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

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

答案 2 :(得分:0)

首先创建数组变量,然后像下面那样对该变量进行stringfy:

$(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);
    }
 });
});