12.3 天气查询
天气状况与人们的生活密切相关。本节的目标就是构造一个实时天气预报的查询系统。天气查询的页面效果如图12.3所示。天气预报是一种实时性数据,其数据源在此处选择的是问天网。本系统的大致原理是:用户输入要查询的城市,单击“查询”按钮,异步向服务器获得指定城市的天气预报。服务器端则利用Thief类从问天网获取这个城市的天气页面,然后对这个页面内容进行过滤,整理,返回给客户端。

图12.3 天气查询运行效果图
天气查询的主界面文件Weather.aspx页面主要由一个输入框和一个提交按钮组成。界面比较简单,具体代码实现如下:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>天气查询</title>
<script type="text/javascript" src="xmlhttp.js"></script>
<script type="text/javascript">
function getWeather() //查询天气
{
if($("city").value=="") //未填入城市名称
{
alert("请输入城市名!");
return
}
var post="city="+$("city").value; //post的数据
Request.sendPOST("weather.ashx",post,revDetail,null,null); //发送请求
}
function revDetail(req,data) //接收到服务器返回信息后的调用函数
{
var text=req.responseText; //接收返回的文本
if(!text || text=="") //没有数据
{
alert("没有你要查询的数据!");
return;
}
$("content").innerHTML=text; //显示返回的内容
}
</script>
</head>
<body>
<div>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="80" colspan="3" align="center" valign="middle">
<br />
<h2>
天气预报查询</h2>
<span>
<br />
请输入城市:</span>
<input type="text" class="bd2" id="city" />
<input type="button"
onclick="getWeather()" class="bd" value=
"查询" />
<center style="color: Red; font-size:
20px; display: none"
id="loadingflag">
正在查询天气状况......</center>
<div id="content" class="content2">
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
Weather.ashx文件则负责从问天网获得天气情况然后返回给异步调用的客户端。详细代码如下:
<%@ WebHandler Language="C#" Class="weather" %>
using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;
//获得天气预报的handler
public class weather : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain"; //返回的文本类型
string post = Tools.getpost(); //获得post的数据
string xmlstr = Thief.Get("http://weather.tq121.com.cn/detail.php?" + post); //取得远程页面的内容
//用于匹配的正则表达式
string temp = "<table width=\"790\" height=\"2101\" border=\"0\" align=\"center\" cellpadding=\"5\" cellspacing=\"0\" bgcolor=\"#94CEEF\">[\\s\\S]*?(?=<table width=\"790\" height=\"100\" border=\"0\" align=\"center\")";
xmlstr = Regex.Match(xmlstr, temp, RegexOptions.IgnoreCase).Value;
xmlstr = Tools.delTag(xmlstr, "a", true); //删除超链接
//图片改为绝对路径
xmlstr = Regex.Replace(xmlstr, "(?<=\")(images/)", "http://weather.tq121. com.cn/$1", RegexOptions.IgnoreCase);
xmlstr = Regex.Replace(xmlstr, "\\.\\./(images)", "http://weather.tq121. com.cn/$1", RegexOptions.IgnoreCase);
xmlstr = Tools.delTag(xmlstr, "input", false); //删除input标记
context.Response.Write(xmlstr); //输出
}
public bool IsReusable //不重用
{
get
{
return false;
}
}
}







