AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=2052&pId=-1
Consuming JSON and XML Webservices from an HTML Page using jQuery
page
by Rajesh Toleti
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 28039/ 34

Introduction

    Please read http://aspalliance.com/713 to find the need of consuming webservices from a HTML page. The methodology explained in the above article works only in IE. By February 2011 IE accounts for around 44% while Firefox enjoys a share of 29%.Chrome is in the third place with around 14%.So there is a clear need for a cross browser solution. Here comes the JQUERY…(If you are new to JQUERY, please see the reference section for its official website and tutorials)

 We use JQUERY cross browser capabilities to achieve our objective. In the first part we will explore the consumption of XML webservices and then we will look into JSON webservices in the second part.

Download

 Download JQUERY from this link http://code.jquery.com/jquery-1.4.2.min.js

Note: I have not tested the code with new versions of JQUERY yet. You can download new versions and experiment. I have used minified version of JQERY for faster execution, but it is not very user-friendly to read. If you want to read the code inside JQUERY, please download uncompressed version. In your code you can refer to uncompressed version as well, but obviously it takes bit more time to execute.

All the versions are available at http://docs.jquery.com/Downloading_jQuery

 

Caution

  This article deals with the scenario where both client (HTML page) and webservices reside on the same server. This may work with the webservices on different servers, if they allow cross-domain requests.

 

PART1 (XML Webservices)

I am going to use a simple webservice(This is included in 'Download Code' section, called Service1.asmx), which will emit the below XML code when it is invoked.

I am not going explain about building that webservice as it is out of scope for this article.

However it is very simple and easily understandable.

Listing 1

<ArrayOfCountryDetails>
<CountryDetails>
<Name>USA</Name>
<Capital>Washington</Capital>
</CountryDetails>
<CountryDetails>
<Name>UK</Name>
<Capital>London</Capital>
</CountryDetails>
<CountryDetails>
<Name>India</Name>
<Capital>New Delhi</Capital>
</CountryDetails>
</ArrayOfCountryDetails>

 

As you can see this XML file contains 3 countries and their capitals. We are going to invoke this webservice from our JQuery code and write the response in a simple table format.

 

Listing 2

        <script src="JS/jquery-1.4.2.min.js" language="javascript"></script>
        <script type="text/javascript">
        $(document).ready(function() {
                     $.ajax({
 
                    type: "POST",       
                   url: "service1.asmx/XMLCountry",       
                   success: function(XMLResponse) { 
                                 var content =
"<table cellspacing=0 border=1><tr><td><strong>Country</strong></td> <td>" +
                     "<strong>Capital</strong></td></tr>";
                     $(XMLResponse).find('ArrayOfCountryDetails').each(function(){
        
                       $(this).find('CountryDetails').each(function(){
                        var name=$(this).find('Name').text();
                        var capital=$(this).find('Capital').text();
                        content=content+"<tr><td>"+name+"</td> <td> "+capital+"</td></tr> " 
                                                                               });
             });
 
 
            content = content + " </table> ";
 
            $("#XMLContent").html(content);           
                                                 },
        error: function(msg) {
            alert('Error occurred');
                              }
                         });
                          })
    </script>

Place the JQUERY reference in HEAD section of the HTML page.

The first line under '<script type="text/javascript">' is the starting point for a JQUERY

i.e  "  $(document).ready(function() { "

This line is very important as it enables the code below it to execute after DOM of the page loaded. It executes before the contents of the web page loaded. You can visualize this as counterpart to traditional <Body ONLOAD="SomeFunction">. We use the built-in ajax event handler to invoke the webservice ie ' $.ajax({'

In JQUERY lingo, we call it as event handler instead of a method or function. The elements inside the event handler are called Settings. Settings are basically key/value pairs.

 

The first Setting is 'type'. The value we have to give is 'POST' .The post is the default setting for any Asp.net webservice. You can use 'GET', if you enable your webservice to accept 'GET' requests.

NOTE: The values are not case sensitive.

  The second setting is URL. The value we provide is the URL to the webservice. In our example 'Service1.asmx' is the Webservice name.' XMLCountry' is the method name. This method does not take any arguments.

  The third setting is 'success'. The value for this key will be a function unlike the above two settings. The function has a parameter, in our example we are calling it as 'XMLResponse'. This can be any name. This parameter contains the XML string, which was emitted by Webmethod 'Service1.asmx/XMLCountry'.

You can use that XML as you like. In our example we will display the values in HTML table

 So we will iterate through the XML string and capture the values of Country name, capital.

"ArrayOfCountryDetails" is the Root of the XML document. 'CountryDetails' is the child which has 'name', 'capital' as sub children.

The variable 'Content' is a simple html string. We build a HTML Table and insert the Country name, capital  as shown in the Listing2.

 We place a Division in HTML page like the below

           <div id="XMLContent"></div>

          We will place HTML content in that division in this way

            $("#XMLContent").html(content);

      If the code runs successfully, you should see a table with 3 countries and their capitals.

  The final setting is 'error'. This is an optional setting. If you want capture any errors occurred during the execution, you can define function as seen in the example. In our example, we are throwing a simple alert.

 

PART2 (JSON Webservices)

We will use the same webservices but a different web method (service1.asmx/JSONCountry) which emits JSON when it is invoked. The JSON string showed in the Listing3

 

Listing 3

      [{"Name":"India","Capital":"NewDelhi"},{"Name":"UK","Capital":"London"},
{"Name":"France","Capital":"Paris"}]
  

 

As you can see this JSON string contains 3 countries and their capitals. We are going to invoke this webservice from our JQuery code and write the response in a simple table format like in the PART1

 

Listing 4

 

        <script src="JS/jquery-1.4.2.min.js" language="javascript"></script>
        <script type="text/javascript">
        $(document).ready(function() {  
                     $.ajax({
        type: "Post",       
        url: "service1.asmx/JSONCountry",        
        contentType: "application/json; charset=utf-8",
        success: function(msg) { 
            var data = $.parseJSON(msg.d); 
            var content = "<table cellspacing=0 border=1>" + 
"<tr><td><strong>Country</strong></td> <td> <strong>Capital</strong></td></tr> " ;
           $.each(data, function(i) { 
                content = content + " <tr> <td> " + data[i].Name + "</td> <td> " +
                    data[i].Capital+ "</td> </tr> ";
                                                      });
            content = content + " </table> ";
            $("#JSONContent").html(content); 
                                           },
        error: function(msg) {
        alert('Error occurred');
                                    }
 
                         });
        
                                 })
    </script>

 

The first few lines of code are same as in Listing 2 with the same explanation. So let us start from the settings. The first setting is 'type' and the value is 'Post'.

The second setting is 'url' and the value is 'service1.asmx/JSONCountry'. We are calling 'JSONCountry' web method which emits JSON, shown in Listing3.

 

The third setting is 'contentType' and the value is 'application/json; charset=utf-8'. Here we are requesting the return data type as JSON.

The fourth setting is 'success'. The value is a function, which take the JSON and convert it to a string. The parameter in this function is 'JSONResponse'. This can be any name.

The first line of the code within the function is very important. ie

"var data = $.parseJSON(JSONResponse.d);"

Here parseJSON method is used, as name suggests it parses 'JSONResponse' into a variable called 'data'. Instead using JSONRepsone directly, we should use 'd' attribute. Please visit the links in the Reference section for more explanation about this 'd' attribute. Same as in Part1 we create the string 'content' and build HTML table. We will run through each element in the variable 'data' using '$.each' function. Name of the country is obtained by data[i].Name and capital is by data[i].Capital. As shown in the above listing we add them in the html table. We declare a division with id 'JSONContent' in the body of HTML page. We will place HTML content in that division in this way      

             $("#JSONContent").html(content);

The last setting is the error, same as explained in the Part1.When you run this page successfully you should be able to see 3 countries and thei capitals in a table.

Summary

      In this way, it is very simple to consume webservices whether their response is either XML or JSON. JQUERY is cross browser compatible and works with all major browsers. There are some JSON, XML webservices available for testing from 'Google maps'. Check the REFERENCE section. One more interesting thing I want to mention is we can call any number of webservices from different places , different formats and can display easily in the same page. In the download section, the HTML page shows both JSON, XML webservices. We can use the same method in ASP.net 2.0/3.5/4.0 to consume webservices without any server side code.

References

http://en.wikipedia.org/wiki/Usage_share_of_web_browsers

http://jquery.org/

http://json.org/

http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/#comment-34045

http://code.google.com/apis/maps/documentation/webservices/



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-19 2:31:16 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search