页面头部有一个天气情况需要显示,原本使用的是iframe框架加载别人的天气信息来显示,发现会有点慢,而且还带有超链接,不好控制,就自己通过中国天气网查询到了返回对应城市的天气信息url,返回的格式是json的,但是不知道为什么直接用ajax不能获取正确,没办法,只能靠程序获取了。不多说,上代码。
把天气信息放入.net缓存中 这是效果。

//获取天气
$.ajax({
url: "/class/Get_Weather.ashx",
type: "POST",
dataType: "JSON",
error: function () { alert("请求失败"); },
success: function (data) {
var weahtml = data.weatherinfo.city + " "
+ data.weatherinfo.date_y + " "
+ data.weatherinfo.week + "<br/>今天:"
+ data.weatherinfo.temp1 + " "
+ data.weatherinfo.weather1 + " "
+ data.weatherinfo.wind1 + " "
+ data.weatherinfo.fl1 + "<br/>明天:"
+ data.weatherinfo.temp2 + " "
+ data.weatherinfo.weather2 + " "
+ data.weatherinfo.wind2 + " "
+ data.weatherinfo.fl2 + "<br/>后天:"
+ data.weatherinfo.temp3 + " "
+ data.weatherinfo.weather3 + " "
+ data.weatherinfo.wind3 + " "
+ data.weatherinfo.fl3 ;
$(".H-Server").html(weahtml);
},
async: true
});
这是前台js代码,用的ajax获取一般处理程序中的天气字符串。
HttpContext httpContext;
public void ProcessRequest (HttpContext context) {
httpContext = context;
//先判断缓存中是否保存有 key为weatherinfo的缓存值
if (httpContext.Cache["weatherinfo"]==null)//如果没有,就调用获取天气的方法
{
GetResponseStr();
}
else { //如果有就直接从缓存中拿值
context.Response.ContentType = "text/plain";
context.Response.Write(httpContext.Cache["weatherinfo"].ToString());
context.Response.End();
}
}
/// <summary>
/// 获得天气的信息(json格式)
/// </summary>
/// <returns></returns>
private void GetResponseStr()
{
httpContext.Response.ContentType = "text/plain";
string str = "http://m.weather.com.cn/data/101180101.html";//访问中国天气网地址,101180101是郑州编码
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(str);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();//获得回应的数据流
//将数据流转成 String
string result = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
//天气信息存入缓存,保存半个小时,短时间内天气信息不会改变
httpContext.Cache.Insert("weatherinfo",result,null,DateTime.Now.AddMinutes(30),TimeSpan.Zero);
httpContext.Response.Write(result);
httpContext.Response.End();
}
这是一般处理程序中的代码。
为了不每次都去访问中国天气网获取天气信息,所有先把获取到的值放入缓存中,保存半小时,这样会提高点速度。
欢迎加入.net学习交流群。