導語:解決跨域問題,前后端都增加相應的允許跨域的代碼段即可。
一、后端增加允許跨域的代碼,可以在具體controler層加,最好是在filter中添加,這樣添加一次就夠了,不用在每個controler中都添加了,代碼截圖如下:
代碼如下:
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
//指定本次預檢請求的有效期,單位為秒
response.setHeader("Access-Control-Max-Age", "86400");
//如果存在自定義的header參數,需要在此處添加,逗號分隔
response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, " +
"Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
//允許跨域請求中攜帶cookie
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("XDomainRequestAllowed","1");
二、前端增加允許跨域的代碼,這里使用的ajax.代碼截圖如下:
代碼如下:
$.ajax({
url: "http://192.168.10.23:8080/hms/jkpgJkzd.do?action=getMbsdList",
type: "get",
crossDomain: true,
xhrFields: {
withCredentials: true
},
dataType: "json",
data: {
"yngrbsh":"31010920090306250337209",
"pglsh":"157a0a07-73e9-450a-b835-3f396b3b7acb",
"jbdms":"JB_GXY;JB_NCZ;JB_TNB_YH"
},
success: function (data) {
alert(data);
alert(JSON.stringify(data));
}
})
至此完成!!!