转载自:http://blog.csdn.net/zhourenfei17/article/details/72312503
对于跨域请求目前常用的有三种方式,1:代理,2:JSONP,3:XHR2,前面两种方式我这边不做介绍,相关的帖子有很多,但是对于XHR2的跨域处理方式很多都介绍的很简单,这边对XHR2处理跨域请求做一个简单的讲解。
首先先贴js端代码:
-
- function ajaxPost(){
- var xhr = new XMLHttpRequest();
- if (xhr.withCredentials === undefined) {
- return;
- }
-
- xhr.open("POST", "http://localhost:8080/sendMsg");
-
- xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
-
- xhr.onreadystatechange = function () {
- if (xhr.readyState !== 4) return;
- if (xhr.status === 200) {
-
- var data = JSON.parse(xhr.responseText);
- alert(data.msg);
- }
- }
-
- 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;
- }