首页 > Web开发 > 详细

ASP.NET 跨域获取JSON天气数据

时间:2015-01-09 12:25:25      阅读:280      评论:0      收藏:0      [点我收藏+]

前几天做一个门户网站,在首页需要加载气象数据,采用了中央气象局的接口。

刚开始采用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天气数据

原文:http://www.cnblogs.com/wsea/p/4212799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!