Request different data type from Web API with JQuery

XML/JSON in return result of Web API REST service method with JQuery

  • Share

In my previous article Different data type in Web API response of the same method I described how to get different response with HttpWebRequest in C#.

Here I will demonstrate how to achieve the same thing but in JQuery client side code. Since Web API reponds based on accept header value, we can set it in ajax request in JQuery.

First let's deal with XML response. In test HTML docuemnt you cah find as an attachemnt to this article, there are two buttons. First one fetches the data in XML format.

 $.ajax({
                url: "http://localhost:6060/api/values",
                headers: {
                    Accept: "text/xml; charset=utf-8",
                    "Content-Type": "text/xml; charset=utf-8"
                },
                success: function (response) {
                    alert(new XMLSerializer().serializeToString(response.documentElement));
                }
            });
    

To be able to display xml result in an alert I had to convert XML document in response variable to a string using XmlSerializer

new XMLSerializer().serializeToString(response.documentElement)
    

Getting JSON value is pretty much the same except accept type and deserialization of result for dusplay purposes in an alert.

$.ajax({
                url: "http://localhost:6060/api/values",
                headers: {
                    Accept: "application/json; charset=utf-8",
                    "Content-Type": "application/json; charset=utf-8"
                },
                success: function (response) {
                    alert(JSON.stringify(response));
                }
            });
    

And againg converting to string to be aple to display in an alert

JSON.stringify(response)
    

Whole solution (HTML docuemnt you can find as a download for this article).

References

  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus