服务端代码
@RequestMapping("/checkImgCode")
@ResponseBody
public String checkImgCode(String imgCode,String mobile,HttpServletRequest request ,HttpServletResponse response) throws IOException {
String message="fail";
Integer respCode=Constants.SERVER_INNER_ERRORCODE;
Result result=new Result(respCode,message);
//这里省略一些业务代码.........
response.setHeader("Access-Control-Allow-Origin", "*");
// 响应类型
response.setHeader("Access-Control-Allow-Methods", "POST");
// 响应头设置
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
//设置允许跨域传输cookie
response.setHeader("Access-Control-Allow-Credentials","true");String s = JSON.toJSONString(result);
//配合ajax跨域请求
String string=" successCallback ("+s+")";
return string;
}
前端代码
$.ajax({
type:"get",
async : true,
dataType:'jsonp',
jsonp:'callback',
jsonpCallback:"successCallback",//这个名字跟后台名字需要匹配
xhrFields: {
withCredentials: true
},
crossDomain: true,
url:springbootUrl+'/book/checkImgCode?mobile='+mobile+'&imgCode='+imgCode,/*url写异域的请求地址*/
success:function(data){
}
Tips:
经过测试windows谷歌浏览器等常用浏览器无问题,大部分安卓设备也无问题,可是到了ios系统safari浏览器出现了session不一致问题,每跨域请求一次都刷新了sessionId,可在ios系统设置里safari浏览器>隐私与安全>阻止跨网站跟踪(关闭此选项)