|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionIn my first article "Ajax Tutorial for Beginners: Part 1" which you can read here, I discussed Ajax, how it works, and how to create an If you are hearing this word, "JSON," for the first time, please do not worry about it as it is more simple than XML and also simple to use in JavaScript. I will not describe: What is JSON? How is it formed? When was it started? bla bla bla... All I will say to you guys is that it is a lightweight data-interchange format, which is easy to read and write. Now let's be more practical. Learn to Convert any XML File into JSONLet's quickly have a look into the following XML file. < weatherdetails>
< weatherreport city="Mumbai" weather="32" ></weatherreport>
< weatherreport city="Delhi" weather="28" ></weatherreport>
< weatherreport city="Chennai" weather="34" ></weatherreport>
< weatherreport city="Kolkata" weather="26" ></weatherreport>
< /weatherdetails>
This XML file gives weather details of the four major cities in India. Let's learn some basic things about how to convert this XML file into JSON.
See that above code XML: < weatherdetails>yyy< /weatherdetails>
Note: I have replaced the inside part of JSON: From the conversion table, JSON will be: { "weatherdetails" : "yyy" },
Isn't it simple? Yes. Ok, now what if we have attributes inside the tag? Let us take another scenario.
See the above code XML: < weatherreport city="Mumbai" weather="32" >< /weatherreport><br>
JSON: from the conversion table, JSON will be { "weatherreport" : {"city":"Mumbai",
"weather":"32"} }
Now what if we have an array of the same tags. If this is the case, we have to use an array and place all the tags inside { "weatherreport" :
[
{"city": "Mumbai", "weather": "32" },
{"city": "Delhi", "weather": "28" },
{"city": "Chennai", "weather": "34" },
{"city": "Kolkata", "weather": "26" }
]
}
Now in the first scenario, I have replaced all { "weatherdetails":
{
"weatherreport":
[
{"city": "Mumbai", "weather": "32" },
{"city": "Delhi", "weather": "28" },
{"city": "Chennai", "weather": "34" },
{"city": "Kolkata", "weather": "26" }
]
}
}
Yes that's it, we have converted an XML file into JSON. Now let's use this XML and JSON file into Ajax together. How Can we Use Ajax with XML Response and with JSONIn the code, I have explained that the response coming from the web server depends upon user selection, i.e. whether the user will select XML type or JSON. In this example, the user will type any one of the major cities in a textbox which will return the weather report of that city. You can add as many details as you want, right now I have only added weather temperature in degrees Celsius. Ok let's start our weather report example in Ajax. See the below figure-1.
Ok, let's start building some front end for the user. < form id="form1" runat="server">
< div>
< h3>Small Ajax Application using XML & JSON to see the Weather
of a particular city < /h3>< br />
< h5>( At present weather details is limited to four major cities
of India i.e. mumbai, delhi, chennai & kolkata )</h5>
< br />
Choose Type here :
< asp:DropDownList runat="server" ID="ddlType" >
< asp:ListItem Value="XML" Selected="True" >XML
< /asp:ListItem>
< asp:ListItem Value="JSON">JSON< /asp:ListItem>
< /asp:DropDownList>
< br />< br />
Type the city here: < input type="text" id="txtCity"
onkeyup="FetchWeather(this.value)" />
< br />
< asp:Label runat="server" ID="lblWeather" />
< /div>
< /form>
Now let's have a look to our Ajax var xmlHttpRequest;
var type;
var _City;
function FetchWeather(city)
{
_City = city.toLowerCase();
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() :
new ActiveXObject("Msxml2.XMLHTTP");
if (xmlHttpRequest == null)
return;
var ddlType = document.getElementById('ddlType');
type = ddlType.options[ddlType.selectedIndex].text;
xmlHttpRequest.open("GET",
"FetchWeather.aspx?city="+city+"&type="+type, true);
if(type=='XML')
xmlHttpRequest.onreadystatechange = StateChangeForXML;
else if(type=='JSON')
xmlHttpRequest.onreadystatechange = StateChangeForJSON;
xmlHttpRequest.send(null);
}
function StateChangeForXML()
{
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
document.getElementById(
'<%= lblWeather.ClientID %>').innerHTML =
xmlHttpRequest.responseText;
document.getElementById('txtCity').focus();
}
}
function StateChangeForJSON()
{
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
var json = eval('('+ xmlHttpRequest.responseText +')');
for(var i=0; i < json.weatherdetails.weatherreport.length; i++)
{
if(
json.weatherdetails.weatherreport[i].city.toLowerCase() ==
_City)
{
document.getElementById(
'< %= lblWeather.ClientID %>').innerHTML =
'< br>Weather Report using JSON< br>
'+json.weatherdetails.weatherreport[i].weather+
'< sup>o< /sup> C <
img src="AjaxTutorial2/weathericon.JPG"
alt="weather" />';
document.getElementById('txtCity').focus();
}
}
}
}
I will explain the above code in small parts in a sequential manner.
Let's have a look at our callback functions: function StateChangeForXML()
{
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
document.getElementById('<%= lblWeather.ClientID %>').innerHTML =
xmlHttpRequest.responseText;
document.getElementById('txtCity').focus();
}
}
function StateChangeForJSON()
{
if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
var json = eval('('+ xmlHttpRequest.responseText +')');
for(var i=0; i < json.weatherdetails.weatherreport.length; i++)
{
if(
json.weatherdetails.weatherreport[i].city.toLowerCase() ==
_City)
{
document.getElementById(
'< %= lblWeather.ClientID %>').innerHTML =
'< br>Weather Report using JSON< br>
'+json.weatherdetails.weatherreport[i].weather+
'< sup>o< /sup> C <
img src="AjaxTutorial2/weathericon.JPG" alt="weather" />';
document.getElementById('txtCity').focus();
}
}
}
}
In FetchWeather.aspx.cs the on if ( type == "XML" )
{
nodeList = doc.SelectNodes( "weatherdetails/weatherreport" );
foreach ( XmlNode node in nodeList )
{
list2Ret.Add( new KeyValuePair<string, string>(
node.Attributes["city"].InnerText.ToLower(),
node.Attributes["weather"].InnerText ) );
}
for ( int i = 0; i < list2Ret.Count; i++ )
{
if ( list2Ret[i].Key == city.ToLower() )
Response.Write("< br>Weather Report using XML < br>
"+ list2Ret[i].Value + "< sup>o< /sup> C"+ weatherIcon );
}
}
else if ( type == "JSON" )
{
string toJSON = byLibrary.byComponent.XmlToJSON( doc );
Response.Write( toJSON );
}
History
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||