1、需求:
通过调用百度的接口,来获取本地的疫情消息,能够实现通过输入日期,显示当前输入日期的新增本土人数。
2、分析:
1)、找到百度接口
直接百度“哈尔滨疫情”,进入详情页面。
f12打开控制台,点击网络(或者network),刷新页面。找到我们需要的请求。
点击预览。
可以看到这条请求返回了我们需要的数据,复制改url,到时候我们本地请求该url就可以了,这里就不分析数据了,代码中有注释解释。
2)、解决跨域问题
跨域问题这里就不解释了,使用jquery配合jsonp实现跨域请求百度数据。跨域和jsonp可以csdn或者百度了解以下。
3、代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>哈尔滨新增本土数据查询</title>
</head>
<body>
<div class="main">
<h1>哈尔滨新增本土数据查询</h1>
输入查询日期:(格式为12.8): <input type="text" id="date"> <br>
<button onclick="query()">查询</button>
<div class="result">
<h1>查询结果:</h1>
<h2 style="color: red;" id="res"></h2>
</div>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
var List = [];//每日新增人数数组
var dateList = [];//日期数组
// dataList[i] 对应 List[i-7]
$(function(){
$.ajax({
url:"https://voice.baidu.com/newpneumonia/getv2?from=mola-virus&stage=publish&target=trendCity&area=%E9%BB%91%E9%BE%99%E6%B1%9F-%E5%93%88%E5%B0%94%E6%BB%A8&callback=jsonp_1639013175048_98469",
type: "GET",
dataType: "jsonp",
success: function(res){
List = res.data[0].trend.list[1].data;
dateList = res.data[0].trend.updateDate;
console.log(res.data);
}
})
})
function query(){
var queryDate = $('#date').val();//输入框中的日期
for(let i=0; i<dateList.length; i++){
if(dateList[i]===queryDate){
console.log(List[i-7]);//找到新增人数
$("#res").append(queryDate+' 日新增 '+List[i-7] + ' 人!<br>');
}
}
}
</script>
</html>
4、结果演示:
一个简易的查询系统就完成了!
可以将url换成自己所在地区的url,url获取参考前面2、分析
的部分。