跨域的简单研究
跨域的解决方案:
1,使用jsonp来解决;
2,使用cros来解决;
分别写两个例子:
比如 x.3333.cn
普通访问 get
jsonp访问 get
cros访问 post
访问 x.4444.cn 的某个接口
http://x.4444.cn/helloJsonP.do 支持jsonp的接口
http://x.4444.cn/helloCros.do 支持cros的接口
分别进行测试,观察:
科普下知识点:
jsonp 利用页面中创建<script>节点的方法向不同域名提交http请求的方法叫做 jsonp;
实现原理:
![]() |
cors cross origin resource sharing 跨域资源共享,
实现原理: 可以让ajax实现跨域访问,只需要服务器端返回一个响应头即可;
![]() |
关键的后端代码:
1 package test.helper; 2 3 import com.google.gson.Gson; 4 import javafx.scene.chart.PieChart; 5 import test.model.response.LoginResponse; 6 7 import javax.servlet.http.HttpServletRequest; 8 import javax.servlet.http.HttpServletResponse; 9 import java.io.IOException; 10 11 /** 12 * Created by carter on 2016/3/29. 13 */ 14 public final class ResponseHelper { 15 16 /** 17 * 写回json数据到客户端,如果是字符串或者int ,long 直接原样写回去 18 * @param response 19 * @param responseData 20 */ 21 public static void write(HttpServletResponse response, Object responseData) { 22 23 String responseMsg = getJsonString(responseData); 24 25 writeString(response, responseMsg); 26 27 28 } 29 30 /** 31 * 返回jsonp数据 32 * @param request 33 * @param response 34 * @param responseMsg 35 */ 36 public static void writeJsonp(HttpServletRequest request, HttpServletResponse response,Object responseMsg) { 37 38 String jsoncallback = request.getParameter("jsoncallback"); 39 40 String jsonString = getJsonString(responseMsg); 41 42 if(null !=jsoncallback && !"".equals(jsoncallback)) 43 { 44 jsonString = jsoncallback + "(" +jsonString+")"; 45 } 46 47 writeString(response,jsonString); 48 49 50 } 51 52 53 private static void writeString(HttpServletResponse response, String responseMsg) { 54 try { 55 response.getWriter().write(responseMsg); 56 } catch (IOException e) { 57 e.printStackTrace(); 58 } 59 } 60 61 private static String getJsonString(Object responseData) { 62 String responseMsg = ""; 63 64 if(null == responseData) 65 { 66 responseMsg = "responseData is empty"; 67 } 68 else 69 { 70 if(responseData instanceof String || responseData instanceof Integer || responseData instanceof Long ) 71 { 72 responseMsg = String.valueOf(responseData); 73 } 74 else 75 { 76 responseMsg = new Gson().toJson(responseData); 77 } 78 } 79 return responseMsg; 80 } 81 82 83 /** 84 * 提供cros支持 85 * @param response 86 * @param data 87 */ 88 public static void writeCors(HttpServletResponse response, Object data) { 89 90 response.addHeader("Access-Control-Allow-Origin","*"); 91 response.addHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS"); 92 response.addHeader("Access-Control-Allow-Headers","Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,X-E4M-With"); 93 94 writeString(response,getJsonString(data)); 95 } 96 }
关键前端代码:
jsonp的:
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>jsonp方式访问接口</title> 5 </head> 6 <body> 7 <button class="cliMe">点我</button> <br> 8 <h1 class="hello"> hello</h1><br> 9 <jsp:include page="common/back.jsp" flush="false"/> 10 </body> 11 <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> 12 <script type="text/javascript"> 13 $(function(){ 14 15 $(".cliMe").bind("click",function(){ 16 $.ajax({url:'http://y.4444.cn:8080/helloJsonp', 17 type:'get', 18 async: false, 19 dataType:'jsonp', 20 jsonp:'jsoncallback', 21 jsonpCallback:'callback'+new Date().getTime(), 22 success:function(data) 23 { 24 $(".hello").empty().html('hello , dear '+ data.username + " , you age is " + data.age); 25 }, 26 error:function(){alert('error');} 27 }); 28 29 }); 30 31 }); 32 </script> 33 </html>
cors访问的前端代码:
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <html> 3 <head> 4 <title>cors方式访问接口</title> 5 </head> 6 <body> 7 <button class="cliMe">点我</button> <br> 8 <h1 class="hello"> hello</h1><br> 9 <jsp:include page="common/back.jsp" flush="false"/> 10 </body> 11 <script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> 12 <script type="text/javascript"> 13 $(function(){ 14 15 $(".cliMe").bind("click",function(){ 16 17 var url = 'http://y.4444.cn:8080/helloCors'; 18 var xhr = createCORSRequest('POST', url); 19 if (!xhr) { 20 alert('CORS not supported'); 21 return; 22 } 23 24 // 回应处理 25 xhr.onload = function() { 26 var text = xhr.responseText; 27 var data = JSON.parse(text); 28 $(".hello").empty().html('hello , dear '+ data.username + " , you age is " + data.age); 29 }; 30 31 xhr.onerror = function() { 32 alert('Woops, there was an error making the request.'); 33 }; 34 35 xhr.send(); 36 37 38 }); 39 40 }); 41 42 function createCORSRequest(method, url) { 43 var xhr = new XMLHttpRequest(); 44 if ("withCredentials" in xhr) { 45 // 针对Chrome/Safari/Firefox. 46 xhr.open(method, url, true); 47 } else if (typeof XDomainRequest != "undefined") { 48 // 针对IE 49 xhr = new XDomainRequest(); 50 xhr.open(method, url); 51 } else { 52 // 不支持CORS 53 xhr = null; 54 } 55 return xhr; 56 } 57 </script> 58 </html>
简单的测试情况:
普通方式:
jsonp方式:
cors方式:
简单的测试小结:
1,使用普通的ajax访问非本域名之外的资源会有跨域问题;
2,jsonp支持get方式的跨域,比较通用;
3,cors支持get,post方式的跨域;但是取决于浏览器的版本限制;
4,更深入的研究,可以参阅Http权威指南。
no pays,no gains!