首页 > 代码库 > 使用API查询天气

使用API查询天气

服务端代码

 [HttpPost]        public ActionResult GetWeather()        {            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://api.map.baidu.com/telematics/v3/weather?location=厦门&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ");            HttpWebResponse response = (HttpWebResponse)request.GetResponse();            Stream Strstream = response.GetResponseStream();            StreamReader sr = new StreamReader(Strstream);            return Content(sr.ReadToEnd());        }

客户端代码

<input type="button" value=http://www.mamicode.com/"获取天气" id="btnOk" /><div id="divCity" style="display: none">    <span>城市:</span>【<span id="txtCity"></span>】</div><div id="divWeather"></div><script src=http://www.mamicode.com/"../../Scripts/jquery-1.4.4.min.js" type="text/javascript"></script><script type="text/javascript">    $(function () {        $("#btnOk").click(function () {            $.post("Home/GetWeather", {}, function (data, status) {                if (status == "success") {                    var jsonData =http://www.mamicode.com/ $.parseJSON(data);                    if (jsonData.status == "success");                    {                        var jsonResult = jsonData.results;                        var strreslut = " <table ><tr> <th> 日期 </th><th>白天</th><th>夜间</th><th>天气</th><th>风</th><th> 气温</th>  </tr>";                        $.each(jsonResult[0].weather_data, function (index, item) {                            strreslut += "<tr><td>" + item.date + "</td><td><img src=http://www.mamicode.com/‘" + item.dayPictureUrl + "‘/></td><td><img src=http://www.mamicode.com/‘" + item.nightPictureUrl + "‘/></td><td>" + item.weather + "</td><td>" + item.wind + "</td><td>" + item.temperature + "</td></tr>";                        });                        strreslut += "</table>";                        $("#divWeather").html("");                        $("#divCity").css("display", "");                        $("#txtCity").html(jsonResult[0].currentCity);                        $("#divWeather").append(strreslut);                    }                }                else {                    alert("ajax请求失败!");                }            });        });    });</script>