CORS解决ajax跨域问题

前端开发 作者: 2024-08-25 19:30:02
一、介绍 CROS是现在主流解决跨域问题的方案,未来估计也是趋势。1. 跨域资源共享(CORS)Cross-Origin Resource Sharing (CORS) 是W3c工作草案,它定义了在跨域访问资源时浏览器和服务器之间如何通信。CORS背后的基本思想是使用自定义的HTTP头部允许浏览器

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"); %>
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_68562.html
CORS解决ajax跨域问题