简体   繁体   English

从jQuery调用JSON Web服务时出错

[英]Error when calling a json webservice from jquery

I have scoured Google looking for this same issue and I cannot seem to find any help. 我曾搜寻过Google,寻找同样的问题,但似乎找不到任何帮助。 Any assistance is appreciated. 任何帮助表示赞赏。 I have created a webservice asmx in C#: 我已经在C#中创建了一个Web服务asmx:

    [WebMethod]
    [ScriptMethod()]
    public ListObj GetList(string ListName)
    {
        SqlConnection DBConnection = new SqlConnection();
        DBConnection.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString();
        SqlDataReader DBReader = null;
        SqlCommand query = new SqlCommand("SELECT Lists.Text, Lists.Value FROM Lists WHERE ListName = '" + ListName + "'", DBConnection);
        List<string> text_list = new List<string>();
        List<string> value_list = new List<string>();

        DBConnection.Open();
        DBReader = query.ExecuteReader();
        while (DBReader.Read())
        {
            text_list.Add(DBReader["Text"].ToString());
            value_list.Add(DBReader["Value"].ToString());
        }
        DBConnection.Close();

        return new ListObj(text_list, value_list);
    }

i am attempting to call that method using jquery: 我正在尝试使用jquery调用该方法:

      <script type="text/javascript">
        $(document).ready(function () {

            $("#JoeTest").click(function () {
              $.ajax({  
                  type: "POST",
                  url: "/Portals/0/DnnListService.asmx/GetList",
                  data: {ListName: 'TestList'},
                  contentType: "application/json; charset=utf-8",  
                  dataType: "json",  
                  success: function(msg) {  
                      alert("Success: " + msg);  
                  },
                  error: function (msg) {
                      alert("Failed: "+ msg.status + ": " + msg.statusText);
                  }  
              });   
            });

        }); 
    </script>

If I go directly to the asmx I can input my string and get the data back, no problem: http://screencast.com/t/JQmHYoz5c http://screencast.com/t/xDuMJe7v1A 如果我直接进入asmx,则可以输入我的字符串并取回数据,没问题: http : //screencast.com/t/JQmHYoz5c http://screencast.com/t/xDuMJe7v1A

However, the ajax call above is returning an error: 但是,上面的ajax调用返回错误:

{"Message":"An attempt was made to call the method \'GetList\' using a POST request, which is not allowed.","StackTrace":" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\\r\\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} {“ Message”:“试图通过POST请求调用方法\\ u0027GetList \\ u0027。”,“ StackTrace”:“位于System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData ,HttpContext上下文)\\ r \\ n位于System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext上下文,WebServiceMethodData methodData)“,” ExceptionType“:” System.InvalidOperationException“}

Any ideas on what the issue may be? 关于这个问题可能有什么想法?

I figured it out! 我想到了!

Here is what I had to do. 这就是我要做的。 In the jQuery I needed this: 在jQuery中,我需要这样做:

            $("#JoeTest").click(function () {
                $.ajax({  
                    type: "POST",
                    url: "/Portals/0/DnnListService.asmx/GetList",
                    data: '{ ListName: "TestList" }',
                    contentType: "application/json; charset=utf-8",  
                    dataType: "json",
                    success: function(msg) {  
                        alert("Success: " + msg);  
                    },
                    error: function (msg) {
                        alert("Failed: "+ msg.status + ": " + msg.statusText);
                    }  
                });   
            });

Notice the data and the type parameters. 注意数据和类型参数。 And in the C# I needed to change 在C#中,我需要进行更改

[ScriptMethod()]

to

[ScriptMethod]

Thanks to @peanutbutter_lou for the solution! 感谢@peanutbutter_lou为解决方案!

Use: 采用:

          $.ajax({  
              type: "GET",
              ...
          });   

You also have to pass the data in the correct json format. 您还必须以正确的json格式传递数据。 To verify the value of the data parameter you can use JSON Lint . 要验证data参数的值,可以使用JSON Lint Change it like this: 像这样更改它:

data: '{"parameter1" : 1, "parameter2": "string" }'

Note the use of double quotes. 请注意使用双引号。 Also, by passing the data as a string you bypass the jQuery data serialization. 另外,通过将数据作为字符串传递,可以绕过jQuery数据序列化。

I think you need to do this too: 我认为您也需要这样做:

        $("#JoeTest").click(function () {
          $.ajax({
              ...
              data: "{'ListName': 'TestList'}",
              ...
          });   
        });

I've always had to do that with jquery when calling ASP.NET web services. 调用ASP.NET Web服务时,我总是必须使用jquery来做到这一点。

Looks a bit like this question, me thinks: 我认为这个问题看起来有点像:
Using JQuery to call a WebMethod 使用JQuery调用WebMethod

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM