当你的开发是先后端分离时,前台发起ajax请求,请求后台数据时会出现跨域问题,为先后台开发人员带来不少不便,若是你用的是springMVC,那么这个问题在后台很是好解决。javascript
springMVC为咱们提供了@CrossOriginhtml
只须要为想要进行跨域访问的controller加入@CrossOrigin就能正常访问并接收数据java
代码以下:jquery
<DOCTYPE html> <html> <head> <title>测试跨域</title> <script src="./jquery-3.2.1.js"></script> <script type="text/javascript"> var aa=function(){ $.ajax({ url:"http://localhost:8080/setschool/haha", type:"get", success:function(mess){ console.log(mess); $.each(mess.extend.ccc,function(index,c){ $("#div1").append($("<p></p>").text(c.name+"--"+c.age)); }); } }); } </script> </head> <body> <input type="button" id="btn" value="click me" onclick="aa()"> <div id="div1"> </div> </body> </html>
package com.lzy.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.lzy.util.Haha; import com.lzy.util.Msg; @Controller public class TestCorssDomain { @CrossOrigin @ResponseBody @RequestMapping("/haha") public Msg haha() { List<Haha> list=new ArrayList<>(); Haha haha=null; for(int i=0;i<10;i++) { haha=new Haha(); haha.setName("Tom"+i); haha.setAge(i+""); list.add(haha); } System.out.println(list); return Msg.success().add("ccc", list); } }
图片为证:web
若是没有加@CrossOrigin标记控制台就会报以下跨域请求失败信息ajax
Failed to load http://localhost:8080/setschool/bb: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.