用于初学者的 Ajax 教程(带 XML & JSON):第 2 部分






4.83/5 (33投票s)
本文将简要介绍 Ajax 与 XML 和 JSON 的结合。

引言
在我第一篇文章“Ajax 教程:初学者指南:第一部分”中,您可以在此阅读,我讨论了 Ajax、它的工作原理以及如何创建 XMLHttpRequest
对象。现在让我们用 Ajax 做更多的事情。在本文中,我将解释 XML 和 JSON(JavaScript 对象表示法)。解释 XML 和 JSON 技术的目的不是进行比较,而是传播两者的知识,因为我认为许多初学者都知道 XML 但不知道 JSON。
如果您是第一次听到“JSON”这个词,请不要担心,因为它比 XML 更简单,而且在 JavaScript 中也易于使用。
我不会描述:JSON 是什么?它如何形成?何时开始?等等……我只会告诉大家,它是一种轻量级的数据交换格式,易于读写。现在让我们更实际一些。
学习将任何 XML 文件转换为 JSON
让我们快速浏览一下下面的 XML 文件。
< 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>
此 XML 文件提供印度四个主要城市的天气详细信息。让我们学习一些关于如何将此 XML 文件转换为 JSON 的基本知识。
XML | JSON |
< xx>yyy< /xx> |
{ "xx":"yyy" } |
看上面的代码 < xx>
是一个标签,它的值为 yyy
。当转换为 JSON 时,它变成 { "xx" : "yyy" }
。让我们以上面的 XML 文件为例,现在尝试转换它。
XML: < weatherdetails>yyy< /weatherdetails>
注意:我暂时将 < weatherdetails>
的内部部分替换为 yyy
。
JSON:从转换表中,JSON 将是
{ "weatherdetails" : "yyy" },
是不是很简单?是的。
好的,如果标签内有属性怎么办?让我们看另一种情况。
XML | JSON |
< xx yy='nn'>< /xx> |
{ "xx": {"yy":"nn"} } |
看上面的代码 <xx>
是一个标签,它有一个属性 yy='nn'
,当我们将它转换为 JSON 时,它变成 { "xx" : {"yy":"nn"}}
。让我们以上面的 XML 文件为例,现在尝试转换。
XML: < weatherreport city="Mumbai" weather="32" >< /weatherreport><br>
JSON: from the conversion table, JSON will be { "weatherreport" : {"city":"Mumbai",
"weather":"32"} }
现在,如果我们有相同的标签数组,该怎么办?在这种情况下,我们需要使用数组并将所有标签放在 []
中。例如,在 XML 文件中,有四个 weatherreport
标签,所以我们必须将所有属性放在一个数组中。让我们看看如何做。
{ "weatherreport" :
[
{"city": "Mumbai", "weather": "32" },
{"city": "Delhi", "weather": "28" },
{"city": "Chennai", "weather": "34" },
{"city": "Kolkata", "weather": "26" }
]
}
在第一种情况下,我已经将所有 weatherreport
标签替换为 yyy
,让我们用上面的 JSON 代码替换它以获得最终的 JSON 输出。
{ "weatherdetails":
{
"weatherreport":
[
{"city": "Mumbai", "weather": "32" },
{"city": "Delhi", "weather": "28" },
{"city": "Chennai", "weather": "34" },
{"city": "Kolkata", "weather": "26" }
]
}
}
是的,就是这样,我们已经将 XML 文件转换为 JSON。现在让我们将这个 XML 和 JSON 文件一起用于 Ajax。
如何将 Ajax 与 XML 响应和 JSON 一起使用
在代码中,我解释了来自 Web 服务器的响应取决于用户的选择,即用户选择 XML 类型还是 JSON。在此示例中,用户将在文本框中键入主要城市之一,这将返回该城市的天气报告。您可以添加任意多您想要的详细信息,目前我只添加了摄氏度的天气温度。
好的,让我们在 Ajax 中开始我们的天气报告示例。请看下图-1。
- Web 浏览器请求页面中仅需要刷新的部分的内容。
- Web 服务器分析接收到的请求,并根据用户的选择构建 XML 消息或 JSON,然后将其发送回 Web 浏览器。
- Web 浏览器收到 XML/JSON 消息后,会解析该消息以更新页面该部分的内容。
好的,让我们开始为用户构建一些前端。
< 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>
- 用户将选择他/她希望从 Web 服务器获得的响应类型。
- 用户将键入他/她希望查看天气报告的城市。
- 在这里,我们在文本框中触发了一个名为 '
onkeyup
' 的事件,该事件将调用FetchWeather()
函数。
现在让我们看看我们必须在 JavaScript 部分编写的 Ajax FetchWeather
函数。
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();
}
}
}
}
我将按顺序分小部分解释上面的代码。
-
从上面的代码开始,我们首先创建一个
XMLHttpRequest
对象xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Msxml2.XMLHTTP");
-
如果浏览器不支持 Ajax,它将返回
false
。 -
接下来,我们使用新创建的
XMLHttpRequest
对象打开与 Web 服务器的连接。这里 FetchWeather.aspx 页面是我们从中获取 XML/JSON 响应的页面(取决于用户的选择)。我以querystring
的形式将城市名称和类型传递给 FetchWeather.aspx 页面。xmlHttpRequest.open("GET", "FetchWeather.aspx?city="+city+"&type="+type, true);
-
根据类型,
XMLHttpRequest
对象将决定调用哪个函数onreadystatechange
。if(type=='XML') xmlHttpRequest.onreadystatechange = StateChangeForXML; else if(type=='JSON') xmlHttpRequest.onreadystatechange = StateChangeForJSON;
让我们看看我们的回调函数。
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();
}
}
}
}
-
xmlHttpRequest.status
属性检索请求的 HTTP 状态码。此属性是只读属性,没有默认值。 -
好的,让我们详细了解 JSON 函数,即
StateChangeForJSON
。来自 Web 服务器的任何文本响应都将通过 JSON eval 过程转换为对象。一旦我们获得对象,我们就可以从中检索任何数据。
-
由于我们发送的请求方法是 "
GET
"(请记住它是区分大小写的),因此无需向服务器发送任何额外信息。//Send the Ajax request to the server with the GET data xmlHttpRequest.send(null);
在 FetchWeather.aspx.cs 的 Page_Load
事件中,会写入以下代码(这是我们的 XML/JSON 响应消息,取决于用户选择的类型)
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 );
}
- 在 XML 类型中,我们将发送用户在 TextBox 中输入的给定城市的天气。这非常简单,正如我在第一篇文章中所解释的,您可以在此阅读。
- 我使用了一个 byLibrary.dll,其中有一个名为
byComponent
的类,该类有一个将 XML 直接转换为 JSON 的方法,该方法接受一个XmlDocument
参数。
XML 输出 | ![]() |
JSON 输出 | ![]() |
历史
- 2008 年 11 月 26 日:首次发布
- 2009 年 1 月 1 日:文章更新