【Java Web开发学习】跨域请求

【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>
上一篇:Java 内部类、成员类、局部类、匿名类等


下一篇:C/C++基础----特殊工具和技术 (重载new和delete,RTT,限定作用域的枚举类型,类成员指针,嵌套类,局部类,volatile,链接指示 extern “C”)