对于跨域请求目前常用的有三种方式,1:代理,2:JSONP,3:XHR2,前面两种方式我这边不做介绍,相关的帖子有很多,但是对于XHR2的跨域处理方式很多都介绍的很简单,这边对XHR2处理跨域请求做一个简单的讲解。
首先先贴js端代码:
//跨域请求方法示例
function ajaxPost(){
var xhr = new XMLHttpRequest();
if (xhr.withCredentials === undefined) {
return;
}
//示例为POST请求
xhr.open("POST", "http://localhost:8080/sendMsg");
//当为post请求时,这段话必须要添加,否则post过去的数据无法正常接收
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;//忽略未完成的调用
if (xhr.status === 200) {
//知道为什么这边接受到的返回值是字符串类型,手动转成json格式,不过这里没有考虑兼容性问题,只是做一个简单的演示
var data = JSON.parse(xhr.responseText);
alert(data.msg);
}
}
//发送请求,并post提交的参数
xhr.send("datas=1231232");
}
服务器端代码:
@RequestMapping("sendMsg")
@ResponseBody
public Json sendMsg(HttpServletResponse response, String datas){
Json json = new Json();
json.setSuccess(true);
json.setMsg("获取数据成功");
System.out.println(datas);
//这里需要设置头信息,不然客户端无法接收到返回值
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
return json;
}
这样就能简单实现post跨域请求了,当然关于XHR2更多的详解介绍和用法(post和get)请参考http://www.cnblogs.com/jelly7723/p/5485635.html