Calling ASP.NET web service function via GET metho

2019-04-28 11:36发布

I'm trying to call web service function via GET method using jQuery, but having a problem. This is a web service code:

[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService  : System.Web.Services.WebService {
    [WebMethod]
    public string Test2()
    {
        string result = null;

    try
        {
            result = "{'result':'success', 'datetime':'" + DateTime.Now.ToString() + "'";
        }
        catch (Exception ex)
        {
            result = "Something wrong happened";
        }

        return result;
    }

}

That's the way I call the function:

$.ajax({ type: "GET",
         url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
         data: "{}",
         contentType: "application/json",
         dataType: "json",
         error: function (xhr, status, error) {
             alert(xhr.responseText);
         },
         success: function (msg) {
             alert('Call was successful!');
         }
     });

Method is called successfully, but result string gets covered by XML tags, like this:

<string>
{'result':'success', 'datetime':'4/26/2010 12:11:18 PM'
</string>

And I get an error because of this (error handler is called). Does anybody know what can be done about this?

7条回答
干净又极端
2楼-- · 2019-04-28 12:14

Make sure to add this to your ajax options:

contentType: "application/json; charset=utf-8"

Your overall request should look like this to get json back instead of XML:

$.ajax({ type: "GET",
     url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
     data: "{}",
     contentType: "application/json",
     dataType: "json",
     contentType: "application/json; charset=utf-8".
     error: function (xhr, status, error) {
         alert(xhr.responseText);
     },
     success: function (msg) {
         alert('Call was successful!');
     }
 });

ScottGu has a full breakdown on what's required here, but it looks like the missing contentType in your case (that one drove me nuts for a while too).

查看更多
登录 后发表回答