頁面頭部有一個天氣情況需要顯示,原本使用的是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學習交流群。