如何在自己写的html访问其他服务器的数据?jsonp解决同源限制,以及访问腾讯天气示例。

jsonp解决同源限制

1.将不同源的服务器端请求地址写在script标签的src属性中
    <script src="www.example.com"></script> 	//script的src特殊,不受同源政策影响

2.服务器端响应数据必须是一个函数的调用,真正要发送给客户端的数据需要作为函数调用的参数。
    const data = ' fn ( {name:"张三", age : "20""} ) ';
    res.send(data) ;

3.在客户端全局作用域下定义函数fn
    function fn (data) { }    //写在引入不同源服务器请求地址script前
    
4.在fn 函数内部对服务器端返回的数据进行处理
    function fn (data) { console. log (data) ; }

示例1:

//html   3000端口下的静态资源
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><title>Document</title>
</head>
<body>
    <script>
    function fn (data){
        console.log(data);
    }
    </script>
    // 1.将非同源服务器端的请求地址写在script标签的src属性中 
    <script src="http://localhost:3001/test"></script>
</body>
</html>

//node.js  监听3001端口的
app.get( '/test', (req,res)=>{
    const result = 'fn({name:"张三"})';
    res.send(result);
}

示例2:访问腾讯天气  -- 利用jsonp

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>使用jsonp获取腾讯天气信息</title>
	<style type="text/css">
		.container {
			padding-top: 60px;
		}
	</style>
</head>
<body>
	<div class="container">
		<table  align="center" id="box"></table>
	</div>
	<script src="./js/jsonp.js"></script>
	<script src="../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>
		// 获取table标签
		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);
			var minute = date.substr(10, 2);
			var seconds = date.substr(12, 2);

			return year + '年' + month + '月' + day + '日' + hour + '时' + minute + '分' + seconds + '秒';
		}

		// 向模板中开放外部变量
		template.defaults.imports.dateFormat = dateFormat;

		// 向服务器端获取天气信息
		jsonp({
			url: 'https://wis.qq.com/weather/common',
			data: {
				source: 'pc',
				weather_type: 'forecast_1h',
				// weather_type: 'forecast_1h|forecast_24h',
				province: '黑龙江省',
				city: '哈尔滨市'
			},
			success: function (data) {
				var html = template('tpl', {info: data.data.forecast_1h});
				box.innerHTML = html;
				
			}
		})
	</script>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值