AJAX方式调用百度天气

后台代码:

        [HttpPost]
        public string AjaxWeather()
        {
            string CityName = string.IsNullOrEmpty(Request.Form["city"]) ? "" : Request.Form["city"].ToString(); //获取城市名称
            if (CityName!="")
            {
                string WeatherInfo = HttpGet(string.Format("http://api.map.baidu.com/telematics/v3/weather?location={0}&output=json&ak=8f6d52bdd67cfe7b6c3db91adb29a51b", HttpUtility.UrlEncode(CityName)));
                return WeatherInfo; //返回JSON
            }
            else
            {
                return "";
            }
        }
#region HttpGet
        /// <summary>
        /// Get方式取信息
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="postDataStr"></param>
        /// <returns></returns>
        public string HttpGet(string Url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }
        #endregion

 

JSON内容:

 1 {
 2     "error": 0,
 3     "status": "success",
 4     "date": "2015-04-28",
 5     "results": [
 6         {
 7             "currentCity": "哈尔滨",
 8             "pm25": "74",
 9             "index": [
10                 {
11                     "title": "穿衣",
12                     "zs": "舒适",
13                     "tipt": "穿衣指数",
14                     "des": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。"
15                 },
16                 {
17                     "title": "洗车",
18                     "zs": "较适宜",
19                     "tipt": "洗车指数",
20                     "des": "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"
21                 },
22                 {
23                     "title": "旅游",
24                     "zs": "适宜",
25                     "tipt": "旅游指数",
26                     "des": "天气较好,温度适宜,但风稍微有点大。这样的天气适宜旅游,您可以尽情地享受大自然的无限风光。"
27                 },
28                 {
29                     "title": "感冒",
30                     "zs": "少发",
31                     "tipt": "感冒指数",
32                     "des": "各项气象条件适宜,无明显降温过程,发生感冒机率较低。"
33                 },
34                 {
35                     "title": "运动",
36                     "zs": "较适宜",
37                     "tipt": "运动指数",
38                     "des": "天气较好,但考虑风力较强且气温较低,推荐您进行室内运动,若在户外运动请注意防风并适当增减衣物。"
39                 },
40                 {
41                     "title": "紫外线强度",
42                     "zs": "中等",
43                     "tipt": "紫外线强度指数",
44                     "des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"
45                 }
46             ],
47             "weather_data": [
48                 {
49                     "date": "周二 04月28日 (实时:25℃)",
50                     "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
51                     "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
52                     "weather": "多云转晴",
53                     "wind": "西南风3-4级",
54                     "temperature": "28 ~ 13℃"
55                 },
56                 {
57                     "date": "周三",
58                     "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
59                     "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
60                     "weather": "晴转多云",
61                     "wind": "南风4-5级",
62                     "temperature": "31 ~ 16℃"
63                 },
64                 {
65                     "date": "周四",
66                     "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
67                     "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
68                     "weather": "晴转多云",
69                     "wind": "西风3-4级",
70                     "temperature": "26 ~ 15℃"
71                 },
72                 {
73                     "date": "周五",
74                     "dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
75                     "nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhenyu.png",
76                     "weather": "阵雨",
77                     "wind": "西南风3-4级",
78                     "temperature": "25 ~ 12℃"
79                 }
80             ]
81         }
82     ]
83 }
View Code

 

Html代码:

城市名称:<input id="city" name="city" type="text" value="@ViewBag.City">
jQuery的Html容器<div id="WeatherHtml"></div>

jQuery代码:

<script type="text/javascript">
    $(function () {
        Weather();
    });

    function Weather() {
        var _city = $("#city").val();
        $.post('/WebApi/AjaxWeather', { city: _city }, function (result) {
            //alert(result);
            var dataObj = eval('(' + result + ')');
            var html = '';
            if (dataObj.status = 'success') {
                $.each(dataObj.results, function (idx, item) {
                    html += '<div>城市名称:' + item.currentCity + '</div>';
                    html += '<div>PM2.5:' + item.pm25 + '</div>';
                    html += '<table>';
                    $.each(item.index, function (idx2, item2) {
                        html += '<tr>';
                        html += '<td>' + item2.tipt + '</td>';
                        html += '<td>' + item2.title + '</td>';
                        html += '<td>' + item2.zs + '</td>';
                        html += '<td>' + item2.des + '</td>';
                        html += '</tr>';
                    });
                    html += '</table>';
                    html += '<table>';
                    $.each(item.weather_data, function (idx3, item3) {
                        html += '<tr>';
                        html += '<td>' + item3.date + '</td>';
                        html += '<td><img src="' + item3.dayPictureUrl + '"/></td>';
                        html += '<td><img src="' + item3.nightPictureUrl + '"/></td>';
                        html += '<td>' + item3.weather + '</td>';
                        html += '<td>' + item3.wind + '</td>';
                        html += '<td>' + item3.temperature + '</td>';
                        html += '</tr>';
                    });
                    html += '</table>';
                });
            }
            $("#WeatherHtml").html(html);
        });
    }
</script>

 

posted @ 2015-04-28 17:03  寂静之秋  阅读(1541)  评论(0编辑  收藏  举报
哈尔滨八零网