1. 跨域资源同享(CORS)
2. CORS与JSONP
-
-
-
1、摹拟跨域要求
<%@ page language="java" contentType="text/html; charset=UTF⑻" pageEncoding="UTF⑻"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
function jsonp_fun(){
$.ajax({
url:'http://localhost:8888/other/index.jsp',type:'post',dataType:'text',success:function(data){
console.log(data);
}
});
}
</script>
</head>
<body>
<input type="button" value="jsonp" onclick="jsonp_fun()"/>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF⑻" pageEncoding="UTF⑻"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
other domain
</body>
</html>
2、设置Access-Control-Allow-Origin
response.setHeader("Access-Control-Allow-Origin","*");
<%@ page language="java" contentType="text/html; charset=UTF⑻"
pageEncoding="UTF⑻"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
<%
response.setHeader("Access-Control-Allow-Origin","*");
%>
other domain
</body>
</html>
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
response.setHeader("Access-Control-Allow-Origin","http://localhost");
3、设置Access-Control-Allow-Methods
<%
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods","GET,POST");
%>
4、设置Access-Control-Allow-Methods
$.ajax({
url:'http://localhost:8888/other/index.jsp',type:'get',success:function(data){
console.log(data);
},xhrFields: { withCredentials: true }
});
<%
response.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
response.setHeader("Access-Control-Allow-Methods",PUT,OPTIONS");
response.setHeader("Access-Control-Allow-Credentials","true");
%>