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.