使用JS通过雅虎的免费RSS服务获取气温
给台北的网站加日历控件,需要每个城市的气候随机显示,但国内大多气温服务都没有提供台湾所有城市,所以还是要找我可爱的雅虎
1:访问http://weather.yahoo.com/ 查找您要获取的城市代码
2:通过 http://weather.yahooapis.com/forecastrss?p=TWXX0028&u=c 的方式,其中 参数P是城市代码,u是温度的单位(u=c:摄氏度)
3:以随机获取下面5个城市温度为例,如下所示:
<script type="text/javascript" language="javascript">
function GetTempTW()
{
document.getElementById('temp').innerHTML = "载入中..";
var cityCode = ['TWXX0028','TWXX0011','TWXX0021','TWXX0019','TWXX0013'];
var cityName = ['台东','花莲','台北','台中','高雄'];
var i = parseInt(Math.random() * 5);
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load("http://weather.yahooapis.com/forecastrss?p="+ cityCode[i] +"&u=c");
var temp= xmlDoc.getElementsByTagName('yweather:condition')[0].getAttribute("temp");
if(temp != "")
{
document.getElementById('temp').innerHTML = cityName[i] + " " + temp;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
</head>
<body>
<div id="temp"></div>
<script type="text/javascript">GetTempTW()</script>
</body>
</html>
function GetTempTW()
{
document.getElementById('temp').innerHTML = "载入中..";
var cityCode = ['TWXX0028','TWXX0011','TWXX0021','TWXX0019','TWXX0013'];
var cityName = ['台东','花莲','台北','台中','高雄'];
var i = parseInt(Math.random() * 5);
var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.load("http://weather.yahooapis.com/forecastrss?p="+ cityCode[i] +"&u=c");
var temp= xmlDoc.getElementsByTagName('yweather:condition')[0].getAttribute("temp");
if(temp != "")
{
document.getElementById('temp').innerHTML = cityName[i] + " " + temp;
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
</head>
<body>
<div id="temp"></div>
<script type="text/javascript">GetTempTW()</script>
</body>
</html>
雅虎的这个服务还有很多其他的信息可供调用,还是比较方便的