當你的開發是先後端分離時,前臺發起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.