Calling ASP.NET web service function via GET method with jQuery

18,579

Enable ASP.NET ASMX web service for HTTP POST / GET requests

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string Test2()
{
   [...]
}
Share:
18,579
the_V
Author by

the_V

Updated on June 12, 2022

Comments

  • the_V
    the_V almost 2 years

    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?