同源策略说明
浏览器中规定 Ajax请求 协议://域名:端口三者必须全部相同时,才能实现数据访问(同域请求) 如果违反上述规则中的任意一个则该请求就是跨域访问.
如果浏览器进行跨域访问,则浏览器不予解析返回值
跨域实现----JSONP
JSONP实现跨域的核心思路是利用javaScript中的src进行跨域
<script type="text/javascript" src="http://manager.jt.com/test.json"></script>
说明:一般src属性负责资源的加载,如果需要使用数据,则需要函数进行调用才行
- 1.定义回调函数
<script type="text/javascript">
/*JS是解释执行的语言 */
/*定义回调函数 */
function hello(data){
alert(data.name);
}
</script>
- 2.将返回值的结果进行特殊格式的封装
说明:返回为hello(参数),相当于在调用函数
hello({"id":"1","name":"tom"})
- 3.JS整体分析
通过src返回的Json会一直保存到浏览器中等待调用,但是如果没有函数名称的话是无法调用的
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试JSON跨域问题</title>
<script type="text/javascript">
/*JS是解释执行的语言 */
/*定义回调函数 */
function hello(data){
alert(data.name);
}
</script>
<!--该json一直保存到浏览器中等待调用,但是没有函数名称无法调用 -->
<script type="text/javascript" src="http://manager.jt.com/test.json"></script>
<script type="text/javascript" src="http://manager.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
</script>
</head>
<body>
<h1>JS跨域问题</h1>
</body>
</html>
JSONP介绍
json胖
JSONP是json的一种使用模式,可用于解决主流浏览器的跨域数据访问的问题(回调函数)
JQuery实现JSONP
使用jQuery负责封装JSONP.像常规ajax调用一样的方便.JSONP的返回值结果必须经过特殊的格式封装
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSONP测试</title>
<script type="text/javascript" src="http://manager.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
alert("测试访问开始!!!!!")
$.ajax({
url:"http://manager.jt.com/web/testJSONP",
type:"get", //jsonp只能支持get请求 src只能进行get请求.
dataType:"jsonp", //dataType表示返回值类型 必须标识
//jsonp: "callback", //指定参数名称
//jsonpCallback: "hello", //指定回调函数名称
success:function (data){ //data经过jQuery封装返回就是json串
alert(data.id);
alert(data.name);
}
});
})
</script>
</head>
<body>
<h1>JSON跨域请求测试</h1>
</body>
</html>
页面请求网址:
编辑Controller(按格式封装返回结果)
@RestController
public class JSONPController {
/**
* 完成JSONP的调用
* url:http://manager.jt.com/web/testJSONP?callback=jQuery111101021758391465013_1597656788213&_=1597656788214
* 规定:返回值结果,必须经过特殊的格式封装.callback(json)
*/
@RequestMapping("/web/testJSONP")
public String jsonp(String callback){
return callback+"({'id':'100','name':'tomcat猫'})";
}
.
CORS跨域访问
CORS是一种允许当前域(domain)的资源(比如html/js/web service)被其他域(domain)的脚本请求访问的机制,通常由于同域安全策略(the same-origin security policy)浏览器会禁止这种跨域请求
JSONP : 用户利用jsonp向服务器端动态获取数据的过程. 主体用户.
CORS: 服务器是否允许客户端访问的技术. 主体服务器
1.常规Ajax跨域
页面会报错,提示服务器端不允许跨域
2.服务器实现CORS跨域
服务器端如果需要实现CORS跨域请求,则需要在服务器端标识允许跨域的网址即可.
3.编辑CORS跨域
package com.jt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration //标识我是一个配置类
public class CorsConfig implements WebMvcConfigurer {
//扩展跨域请求的方法
@Override
public void addCorsMappings(CorsRegistry registry) {
//1.允许什么样的请求进行跨域
// /* 只允许一级目录请求 /** 表示多级目录请求.
registry.addMapping("/**")
//2.允许哪些服务进行跨域
.allowedOrigins("*")
//3.是否允许携带cookie信息
.allowCredentials(true)
//4.定义探针检测时间 在规定的时间内不再询问是否允许跨域
.maxAge(1800);
}
}