
前几天做一个门户网站,在首页需要加载气象数据,采用了*气象局的接口。
刚开始采用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到前台进行处理。
每天记住一点点,方便以后再次使用。