標籤:
前幾天做一個門戶網站,在首頁需要載入氣象資料,採用了中央氣象局的介面。
剛開始採用JSONP在前台跨域請求資料,沒成功~
後換成在c#後台請求資料返回...
前端代碼:
$(function () { $.ajax({ type: "GET", url: "service/getWeather.ashx", dataType: "json", success: function (data) { var weatherMS = ‘‘; console.log(data); data = eval(data.weatherinfo); weatherMS += ‘城市:‘ + data.city+‘ 天氣情況:‘+data.weather+‘ 氣溫:‘+data.temp2+‘~‘+data.temp1; $("#innerWeather").html(weatherMS); } }); })
後台代碼:
context.Response.ContentType = "text/plain"; //擷取天氣和解析 HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.weather.com.cn/data/cityinfo/101110407.html"); request.Timeout = 5000; request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string jsonstr = sr.ReadLine(); context.Response.Write(jsonstr);
直接輸入JSON到前台進行處理。
每天記住一點點,方便以後再次使用。
ASP.NET 跨域擷取JSON天氣資料