使用jsonp向非同源服务器端发送请求数据

使用jsonp向非同源服务器端发送请求数据

jsonp 代码优化

1.客户端需要将函数名称传递到服务器端
2.将script 请求的发送变成动态请求

案例:
02.使用jsonp向同源服务器端请求数据(1).html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script>
		function fn (data) {
			console.log('客户端的fn函数被调用了')
			console.log(data);
		}
	</script>
	<!-- 1.将非同源服务器端的请求地址写在script标签的src属性中 -->
	<script src="http://localhost:3001/test"></script>
</body>
</html>

03.使用jsonp向非同源服务器端请求数据(2).html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<script>
		function fn2 (data) {
			console.log('客户端的fn函数被调用了')
			console.log(data);
		}
	</script>
	<!-- 1.将非同源服务器端的请求地址写在script标签的src属性中 -->
	<script src="http://localhost:3001/better?callback=fn2"></script>
</body>
</html>

03.使用jsonp向非同源服务器端发送请求数据(3).html

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button id="btn">点我发送请求</button>
	<script>
		function fn2 (data) {
			console.log('客户端的fn函数被调用了')
			console.log(data);
		}
	</script>
	<script type="text/javascript">
		// 获取按钮
		var btn = document.getElementById('btn');
		// 为按钮添加点击事件
		btn.onclick = function () {
			// 创建script标签
			var script = document.createElement('script');
			// 设置src属性
			script.src = 'http://localhost:3001/better?callback=fn2';
			// 将script标签追加到页面中
			document.body.appendChild(script);
			// 为script标签添加onload事件
			script.onload = function () {
				// 将body中的script标签删除掉
				document.body.removeChild(script);
			}
		}
	</script>
</body>
</html>

app.js定义:

app.get('/better',(req,res) => {
   //接收客户端传递过来的函数的名称
   const fnName = req.query.callback;
   //将函数名称对应的函数调用代码返回给客户端
   res.send(result);
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值