jsonp跨域访问实战
2017-03-25 本文已影响30人
Dev_yang7
server 端
@RestController
public class Controller1 {
@RequestMapping(value = "/test1",method = RequestMethod.GET)
public String test1(HttpServletRequest request){
String data="'data from server2 which port 8081'";
String jsonpCallback = request.getParameter("jsonpCallback");//这一步很关键
String s=jsonpCallback+"("+data+");";
return s;
}
}
client端
<script>
$(function () {
$("#test1").click(function () {
$.getJSON("http://localhost:8081/test1?jsonpCallback=?",function(data){
console.log(data);
});
});
});
</script>
result:80端口获取到了81端口的数据(跨域访问)
Paste_Image.pngjsonp原理
<script src="..."></script>可以无视跨域访问