后台代码:

        [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内容:

 {
"error": 0,
"status": "success",
"date": "2015-04-28",
"results": [
{
"currentCity": "哈尔滨",
"pm25": "74",
"index": [
{
"title": "穿衣",
"zs": "舒适",
"tipt": "穿衣指数",
"des": "建议着长袖T恤、衬衫加单裤等服装。年老体弱者宜着针织长袖衬衫、马甲和长裤。"
},
{
"title": "洗车",
"zs": "较适宜",
"tipt": "洗车指数",
"des": "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"
},
{
"title": "旅游",
"zs": "适宜",
"tipt": "旅游指数",
"des": "天气较好,温度适宜,但风稍微有点大。这样的天气适宜旅游,您可以尽情地享受大自然的无限风光。"
},
{
"title": "感冒",
"zs": "少发",
"tipt": "感冒指数",
"des": "各项气象条件适宜,无明显降温过程,发生感冒机率较低。"
},
{
"title": "运动",
"zs": "较适宜",
"tipt": "运动指数",
"des": "天气较好,但考虑风力较强且气温较低,推荐您进行室内运动,若在户外运动请注意防风并适当增减衣物。"
},
{
"title": "紫外线强度",
"zs": "中等",
"tipt": "紫外线强度指数",
"des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"
}
],
"weather_data": [
{
"date": "周二 04月28日 (实时:25℃)",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/duoyun.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/qing.png",
"weather": "多云转晴",
"wind": "西南风3-4级",
"temperature": "28 ~ 13℃"
},
{
"date": "周三",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather": "晴转多云",
"wind": "南风4-5级",
"temperature": "31 ~ 16℃"
},
{
"date": "周四",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/duoyun.png",
"weather": "晴转多云",
"wind": "西风3-4级",
"temperature": "26 ~ 15℃"
},
{
"date": "周五",
"dayPictureUrl": "http://api.map.baidu.com/images/weather/day/zhenyu.png",
"nightPictureUrl": "http://api.map.baidu.com/images/weather/night/zhenyu.png",
"weather": "阵雨",
"wind": "西南风3-4级",
"temperature": "25 ~ 12℃"
}
]
}
]
}

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>

AJAX方式调用百度天气的更多相关文章

  1. PHP调用百度天气接口API

    //百度天气接口API $location = "北京"; //地区 $ak = "5slgyqGDENN7Sy7pw29IUvrZ"; //秘钥,需要申请,百 ...

  2. asp.net 通过ajax方式调用webmethod方法使用自定义类传参及获取返回参数

    实体类    public class User    {        public int Id { get; set; }        public string Name { get; se ...

  3. 使用ajax和urlconnection方式调用webservice服务

    <html> <head> <title>使用ajax方式调用webservice服务</title> <script> var xhr = ...

  4. 百度编辑器ueditor通过ajax方式提交,不需要事先转义字符的方法(异常:从客户端(xxx)中检测到有潜在危险的 Request.Form 值)

    最近项目中使用百度编辑神器ueditor,确实是很好用的一款编辑器.官网教程提供的与后端数据交互都是跟表单方式有关的,项目中使用的是ajax方式提交,因此出现了不少问题,现在记录备忘下. 环境:.ne ...

  5. 使用jsonp跨域调用百度js实现搜索框智能提示,并实现鼠标和键盘对弹出框里候选词的操作【附源码】

    项目中常常用到搜索,特别是导航类的网站.自己做关键字搜索不太现实,直接调用百度的是最好的选择.使用jquery.ajax的jsonp方法可以异域调用到百度的js并拿到返回值,当然$.getScript ...

  6. C#以post方式调用struts rest-plugin service的问题

    struts2: 玩转 rest-plugin一文中,学习了用struts2开发restful service的方法,发现用c#以post方式调用时各种报错,但java.ajax,包括firefox ...

  7. SpringMvc 相关,bean map转换,百度天气,base64.js,jsBase64.java;

    1. Map<String, Object>与JavaBean[POJO, Model]转换; //model public class model{ private int id; pr ...

  8. jquery+asp.net 调用百度geocoder手机浏览器定位--Api介绍及Html定位方法

    原文来自:***/projecteactual/jqueryaspnetbaidugeocodermobilebrowserposition.html 在做一个社区项目中,支持移动浏览器进行选择地区和 ...

  9. 使用jsonp跨域调用百度js实现搜索框智能提示(转)

    http://www.cnblogs.com/oppoic/p/baidu_auto_complete.html 项目中常常用到搜索,特别是导航类的网站.自己做关键字搜索不太现实,直接调用百度的是最好 ...

随机推荐

  1. 配置git 环境变量

    1.从Git官网下载windows版本的git:http://git-scm.com/downloads 2.一般使用默认设置即可:一路next,git安装完毕! 3.但是如果这时你打开windows ...

  2. sqlserver,oracle,mysql等的driver驱动,url怎么写

    oracle driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521 ...

  3. fatal error C1083: 无法打开包括文件:“iostream.h”: No such file or directory

    其实 <iostream.h>是c风格的,你可用,但注意格式:  要么是:  #include <iostream>  using namespace std; 在标准C++里 ...

  4. java.lang.IllegalStateException: getOutputStream() has already been called for this response解决方案

    异常产生原因:web容器生成的servlet代码中有out.write(""),这个和JSP中调用的response.getOutputStream()产生冲突.即Servlet规 ...

  5. go cobra

    https://github.com/spf13/cobra https://github.com/spf13/cobra/blob/master/bash_completions.md go get ...

  6. call和callvirt

    call以非虚方式调用虚函数. callvirt以虚方式调用虚函数,调用的时候会判断真正引用的对象,调用该类型的

  7. Miller-Rabin算法

    Miller-Rabin算法用于检测一个数n是否是素数.其时间复杂度上界为O(klog2(n)),其中k为检测的轮数.增大k可以提高Miller-Rabin算法的准确度. 要检测一个数是否为素数,简单 ...

  8. VUE+WebPack游戏设计:'乘法防线'游戏设计

  9. Kubuntu上连接PPTP

    生活在天朝,如果没备几招FQ的本领,都不敢说自己还活着... 前两天从朋友那抢了个VPN帐号,使用的是PPTP的,在google上找了一会,发现网上大都是讲VPN服务搭建的,就算是介绍客户端的,也大都 ...

  10. socket,TCP/IP的理解(转)

    TCP/IP 要想理解socket首先得熟悉一下TCP/IP协议族, TCP/IP(Transmission Control Protocol/Internet Protocol)即传输控制协议/网间 ...