【Java Web开发学习】跨域请求
=================================================
1、使用jsonp
=================================================
代码很简单不做解释
json和jsonp的区别阅读 https://kb.cnblogs.com/page/139725/
package ycx.crossdomain.controller; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; @RestController public class IndexController { @RequestMapping("/") public void index(HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, Object> dataMap = new HashMap<>(); dataMap.put("status", 200); dataMap.put("message", "OK"); dataMap.put("data", "hello world"); ObjectMapper mapper = new ObjectMapper(); String data = mapper.writeValueAsString(dataMap); PrintWriter out = response.getWriter(); String callback = request.getParameter("callback"); if (StringUtils.isEmpty(callback)) { out.print(data); } else { out.print(callback + "(" + data + ")"); } out.flush(); out.close(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>jsonp</title> <script type="text/javascript" src="js/jquery-3.4.1.js"></script> </head> <body> <script> // has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. // $.ajax({ // type: "GET", // async: false, // url: "http://localhost:9902", // success: function (result) { // console.dir(result); // }, // error: function (e) { // console.dir(e); // } // }); $.ajax({ type: "GET", async: false, url: "http://localhost:9902", dataType: "jsonp", jsonp: "callback", jsonpCallback:"handler", success: function (result) { console.dir(result); }, error: function (e) { console.dir(e); } }); </script> </body> </html>