JSONP 跨域请求处理
JSONP(JSON with Padding) 是 JSON 的一种 "使用模式", 可以让网页从别的域名 (网站) 那获取资料, 绕过同源策略(若地址里面的协议, 域名和端口号均相同则属于同源), 即跨域读取数据.
JSONP: 利用 script 标签可以跨域, 让服务器端返回可执行的 JavaScript 函数, 参数为要回发的数据. 可看做带有回调函数的 Ajax 请求.
JS 代码
- <script type="text/javascript">
- $(function(){
- /*
- // 简写形式, 效果相同
- $.getJSON("http://app.example.com/base/json.do?sid=1494&busiId=101&jsonpCallback=?",
- function(data){
- $("#showcontent").text("Result:"+data.result)
- });
- */
- $.Ajax({
- type : "get",
- async:false,
- url : "http:/XXX",
- dataType : "jsonp",// 数据类型为 JSONP
- JSONP: "jsonpCallback",// 服务端用于接收 callback 调用的 function 名的参数
- jsonpCallback:"自定义回调函数名"
- success : function(data){
- alert(data.info)
- },
- error:function(){
- alert('fail');
- }
- });
- });
- </script>
java 后端处理代码
- @ResponseBody
- @RequestMapping(value = "/url", produces= MediaType.APPLICATION_JSON)
- public String test(
- HttpServletRequest request,
- HttpServletResponse response) throws Exception{
- String result = getResult();
- response.setHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "private,no-cache,no-store,max-age=0");
- response.setDateHeader("Expires", 0);
- String str=request.getParameter("jsonpCallback");
- if (str==null||str.equals("")) {
- return result;
- } else {
- return str + "(" + result + ")";
- }
- }
- CORS(协议跨域资源共享 ")(Cross-origin resource sharing)
它允许浏览器向跨源服务器, 发出 XMLHttpRequest 请求, 从而克服了 Ajax 只能同源使用的限制 详细介绍 戳此
Access-Control-Allow-Origin:* 允许所有域名的脚本访问该资源
Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS 运行什么方式访问资源
Access-Control-Expose-Headers:x-requested-with 暴露的信息
来源: https://www.cnblogs.com/chenzd/p/9989682.html