Error when calling a json webservice from jquery

2019-03-03 22:41发布

问题:

I have scoured Google looking for this same issue and I cannot seem to find any help. Any assistance is appreciated. I have created a webservice asmx in C#:

    [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:

      <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

However, the ajax call above is returning an error:

{"Message":"An attempt was made to call the method \u0027GetList\u0027 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"}

Any ideas on what the issue may be?

回答1:

I figured it out!

Here is what I had to do. In the jQuery I needed this:

            $("#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

[ScriptMethod()]

to

[ScriptMethod]

Thanks to @peanutbutter_lou for the solution!



回答2:

Use:

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

You also have to pass the data in the correct json format. To verify the value of the data parameter you can use 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.



回答3:

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.



回答4:

Looks a bit like this question, me thinks:
Using JQuery to call a WebMethod