JSONP案例:腾讯天气

本文介绍了一种使用JSONP技术从腾讯天气API获取实时天气数据的方法,并展示了如何将这些数据动态地显示在一个HTML表格中。具体实现包括定义HTML结构、引入必要的库文件、编写日期格式化函数以及使用JSONP请求数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>使用jsonp获取腾讯天气信息</title>
	<link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
	<style type="text/css">
		.container {
			padding-top: 60px;
		}
	</style>
</head>
<body>
	<div class="container">
		<table class="table table-striped table-hover" align="center" id="box"></table>
	</div>
	<script src="/js/jsonp.js"></script>
	<script src="/js/template-web.js"></script>
	<script type="text/html" id="tpl">
		<tr>
			<th>时间</th>
			<th>温度</th>
			<th>天气</th>
			<th>风向</th>
			<th>风力</th>
		</tr>
		{{each info}}
		<tr>
			<td>{{dateFormat($value.update_time)}}</td>
			<td>{{$value.degree}}</td>
			<td>{{$value.weather}}</td>
			<td>{{$value.wind_direction}}</td>
			<td>{{$value.wind_power}}</td>
		</tr>
		{{/each}}
	</script>
	<script>
		var box = document.getElementById('box');
		
		function dateFormat (date) {
			var year = date.substr(0, 4);
			var month = date.substr(4, 2);
			var day = date.substr(6, 2);
			var hour = date.substr(8, 2);
			return year + '年' + month + '月' + day + '日' + hour+'时';
		}
		//向模板中开放外部变量
		template.defaults.imports.dateFormat = dateFormat;

		jsonp({
			url: 'http://wis.qq.com/weather/common',
			data: {
				source: 'pc',
				weather_type: 'forecast_1h',
				province: '黑龙江省',
				city: '哈尔滨市'
			},
			success: function (data) {
				// console.log(data);
				var html = template('tpl', {info: data.data.forecast_1h});
				// console.log(html);
				box.innerHTML = html;
			}
		})
	</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值