• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Ajax 通过城市名获取数据(全国天气预报API)

jquery 搞代码 4年前 (2021-12-27) 35次浏览 已收录 0个评论

本文给大家分享全国天气预报API Ajax 通过城市名获取数据,通过html和js两部分代码实现天气预报效果,输入城市就会出现天气情况,效果非常棒,感兴趣的朋友可以参考下

预览图(比较简单粗糙)

聚合数据全国天气预报接来源gao@dai!ma.com搞$代^码网口:https://www.juhe.cn/docs/api/id/39

接口地址:http://v.juhe.cn/weather/index
支持格式:json/xml
请求方式:get
请求示例:http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key=您申请的KEY
调用样例及调试工具:API测试工具
请求参数说明:
名称 类型 必填 说明
cityname string Y 城市名或城市ID,如:”苏州”,需要utf8 urlencode
dtype string N 返回数据格式:json或xml,默认json
format int N 未来6天预报(future)两种返回格式,1或2,默认1
key string Y 你申请的key

HTML部分代码:

  <title>天气预报</title><div id="mf_weather"> <button id="search">天气查询</button><div class="ctn"> <div id="mufeng"> </div><div id="future"></div></div>

JavaScript部分:

/*
* 1.输入城市名
* 2,点击的时候发送请求
* 3.响应成功渲染页面
* */
$(‘#search’).on(‘click’,function(){
var city = $(‘#city’).val()||’北京’;
$citycode=urlencode(city);
url=’http://v.juhe.cn/weather/index?format=2&cityname=’+$citycode+’&key=c82727e986a4f6cfc6ba1984f1f9183a&#8217;;
$.ajax({url: url,
dataType: “jsonp”,
type:”get”,
data:{location:city},
success:function(data){
var sk = data.result.sk;
var today = data.result.today;
var futur = data.result.future;
var fut = “日期温度天气风向”;
$(‘#mufeng’).html(“

” + ‘当前: ‘ + sk.temp + ‘℃ , ‘ + sk.wind_direction + sk.wind_strength + ‘ , ‘ + ‘空气湿度’ + sk.humidity + ‘ , 更新时间’ + sk.time + “

” + today.city + ‘ 今天是: ‘ + today.date_y + ‘ ‘ + today.week + ‘ , ‘ + today.temperature + ‘ , ‘ + today.weather + ‘ , ‘ + today.wind + “

“);
$(‘#future’).html(“

” + ‘未来: ‘ + futur[0].temperature+ ‘℃ , ‘ + futur[0].weather + futur[0].wind + ‘ , ‘ + ‘ , 更新时间’ + futur[0].week+futur[0].date + “

” + today.city + “

“);
} });
});
function urlencode (str) {
str = (str + ”).toString();
return encodeURIComponent(str).replace(/!/g, ‘%21’).replace(/’/g, ‘%27’).replace(/\(/g, ‘%28’).
replace(/\)/g, ‘%29’).replace(/\*/g, ‘%2A’).replace(/%20/g, ‘+’);
}
})

以上所述是小编给大家介绍的Ajax 通过城市名获取数据(全国天气预报API),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对gaodaima搞代码网网站的支持!

以上就是Ajax 通过城市名获取数据(全国天气预报API)的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Ajax 通过城市名获取数据(全国天气预报API)

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址