首页 > web前端 > js教程 > 正文

Ajax获取全国天气预报的API数据

php中世界最好的语言
发布: 2018-04-03 11:15:36
原创
3712人浏览过

这次给大家带来Ajax获取全国天气预报的API数据,Ajax获取全国天气预报API数据的注意事项有哪些,下面就是实战案例,一起来看一下。

预览图(比较简单粗糙)

聚合数据全国天气预报接口: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部分代码:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" >
<title>天气预报</title>
<script src="jquery-2.1.1.min.js"></script>
<link rel="stylesheet" href="w.css">
<p id="mf_weather">
<script src="w.js"></script>
<button id="search">天气查询</button>
<input id="city" type="text" value="tbody">
<p class="ctn">
<p id="mufeng">
</p>
<p id="future"></p>
</p> 
</html>
登录后复制

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';
$.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("<p>" + '当前: ' + sk.temp + '℃ , ' + sk.wind_direction + sk.wind_strength + ' , ' + '空气湿度' + sk.humidity + ' , 更新时间' + sk.time + "</p><p style='
padding-bottom
: 10px;'>" + today.city + ' 今天是: ' + today.date_y + ' ' + today.week + ' , ' + today.temperature + ' , ' + today.weather + ' , ' + today.wind + "<p></p>");
$('#future').html("<p>" + '未来: ' + futur[0].temperature+ '℃ , ' + futur[0].weather + futur[0].wind + ' , ' + ' , 更新时间' + futur[0].week+futur[0].date + "</p><p style='padding-bottom: 10px;'>" + today.city + "<p></p>");
} });
});
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, '+'); 
} 
})
登录后复制

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Ajax如何读取txt并对其内容进行分页展示

Ajax遍历jSon进行数据的修改和删除

以上就是Ajax获取全国天气预报的API数据的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号