sessionId所属的站点暴露接口(本机域localhost
):
@GetMapping(value = "/mySessionId")
public void mySessionId(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestedSessionId = request.getRequestedSessionId();
response.addHeader("content-type","text/javascript");
try(PrintWriter writer = response.getWriter()) {
writer.write("var mySessionId = '"+requestedSessionId+"';");
} catch (IOException e) {
e.printStackTrace();
}
}
其它任意站点访问该接口( 菜鸟教程所在域www.runoob.com
):
关键
JSONP 跨域特性
- 使用JQuery的
getScript
函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getScript("http://localhost:8080/mySessionId",function(){alert(mySessionId)});
});
});
</script>
</head>
<body>
<button>使用 Ajax 来获取JavaScript脚本并执行</button>
</body>
</html>