前端:原理,标签的形式可以实现跨域,但是无法接收接口的返回参数。需要接口直接向页面写出回调方法。
//原生: <script> var script = document.createElement('script'); script.type = 'text/javascript'; // 传参并指定回调执行函数为onBack script.src = 'http://www.domain.com:8080/loginuser=admin&callback=onBack'; document.head.appendChild(script); // 回调执行函数 function onBack(res) { alert(JSON.stringify(res)); } </script>
//ajax $.ajax({ url: 'http://www.domain2.com:8080/login', type: 'get', dataType: 'jsonp', // 请求方式为jsonp jsonpCallback: "onBack", // 自定义回调函数名 data: {} });
后端 java
//测试jsonp @GetMapping("/jsonp") public void testJsonp(String functionName, HttpServletResponse httpResponse) throws IOException { httpResponse.setContentType("text/html; charset=utf-8"); httpResponse.getWriter().write(functionName+"({\"status\": true, \"user\": \"admin\"})"); httpResponse.getWriter().flush(); httpResponse.getWriter().close(); }