原理
浏览器在获取script标签的内容时,并不会受到同源策略的限制,即使script的请求url跨域也能获得脚本内容,这时可以提前定义好一个函数,然后动态生成script标签,通过查询参数将函数名传递给服务器,服务器返回这个函数调用,需要获取的数据通过函数参数传递进来
代码实现
- 浏览器端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LearnJS</title>
</head>
<body>
<script>
// 预先定义变量保存执行得到的数据
let data;
function getName(response){
data = response;
console.log(data);
}
// 动态生成script标签
let script = document.createElement("script");
// 把预先定义的函数名通过查询参数的形式传递给服务器
script.src = "http://localhost:8082/jsonp?callback=getName";
// 添加到dom树中后,浏览器会发起请求,获取这个脚本,返回的脚本内容是getName(data);就会调用预先定义的getName函数,想要获得的数据保存在getName的参数中
document.getElementsByTagName("body")[0].append(script);
</script>
</body>
</html>
2.服务器端代码,我使用了java的springboot框架来作为服务器端程序,当收到http://localhost:8082/jsonp?callback=getName请求时,构造js函数调用代码,把数据传递给前端
@RestController
public class TestController {
// 当接收到http://localhost:8082/jsonp?callback=getName时,返回getName("will terner")
@GetMapping("/jsonp")
public String name(@RequestParam("callback") String callback){
String data = "will terner";
return callback + "(\"" + data + "\");";
}
}
测试
原html页面所在的源为http://localhost:8081,要请求的数据的源为http://locahost:8082