頁面頭部有一個天氣情況需要顯示,原本使用的是iframe框架加載別人的天氣信息來顯示,發現會有點慢,而且還帶有超鏈接,不好控制,就自己通過中國天氣網查詢到了返回對應城市的天氣信息url,返回的格式是json的,但是不知道爲什麼直接用ajax不能獲取正確,沒辦法,只能靠程序獲取了。不多說,上代碼。
這是效果。
//獲取天氣
$.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學習交流羣。