ajax 处理跨域方法
解决ajax跨域问题,本人常用的两种方法:
方法一:使用"jsonp"属性
$.ajax({
async:false,
url:loginProject+"chk/ajax/ChkMessage.xhtml",
type:'get',
data:{"aa":"aa"},
dataType:'jsonp',//接收数据格式
jsonp:'callbackFunc',
cache:false,
success:function(){},
error:function(){}
});
注:jsonp方式实现跨域请求,只支持get请求,其中的“callbackFunc”为回调函数名称,可自行命名,但需在服务端配合指明,服务端处理代码如下:
@RequestMapping("/{channel}/ChkMessage.xhtml")
public void getChkMsg(HttpServletRequest request,HttpServletResponse response){
Map<String,String> map = new HashMap<String,String>();
map.put("id","123");
map.put("name","张三");
PrintWriter pw = null;
try{
pw = response.getWriter();
String callBackFun = request.getParameter("callbackFunc");
if(Utils.isNotEmpty(callBackFun)){
response.setHeader("Access-Control-Allow-Origin","*");
pw.write(callBackFun+"("+JSONArray.fromObject(map).toString()+")");
}else{
pw.write(JSONArray.fromObject(map).toString());
}
}catch(IOException e){
logger.error(e.getMessage(),e);
}finally{
if(pw != null){
pw.close();
}
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
方法二:使用"xhrFields"属性
$.ajax({
async:false,
url:loginProject+"chk/ajax/ChkMessage.xhtml",
type:'get',
data:{"aa":"aa"},
xhrFields:{
withCredentials:true
},
cache:false,
success:function(){},
error:function(){}
});