Ajax的跨域请求操作
1.何为Ajax跨域请求?
既然说到跨域请求那首先得弄清楚什么是跨域?跨域通常又分为两种:
1.IP地址不同即比如localhost:8080/XXX请求
192.168..2.10:8090/YYY
的数据;
2.端口号不同即例如localhost:8080/XXX请求localhost:8081/TTT的数据;
2.如何实现ajax的跨域请求?
常见的使用jsonp来处理操作,具体实现流程:
$.ajax({
async:false,
type:"get",
url: "http://localhost:8081/center/test2",
dataType:"jsonp",
jsonp:"callback",
jsonpCallback:"crossDomains",
success:function(json){
alert(json.account);//后台处理的数据
},
error:function(){
alert("跨域请求失败,失败!!");
}
});
后台代码:
@RequestMapping("/test2") @ResponseBody public String test2(HttpServletResponse response,String callback){ System.out.println("tets........"+callback); User user=new User(); user.setAccount("miky"); return callback+"("+JSON.toJSONString(user)+")"; }
1.jsonp与常规json的区别:jsonp = callback + (json);
2.跨域请求与常规传统请求的区别:
2.1传统常规的请求方式:
http://localhost:8081/center/test2?argus(参数)=SSS而跨域请求则不用这样传参,待方法执行完会自动生成http://localhost:8081/center/test2?callback=
crossDomains
2.2跨域请求的type是script,而常规的则是xhr(XmlHttpRequest);