0%

使用jsonp解决跨域问题

在前后端交互的过程中,不可避免遇上跨域问题。跨域问题有很多种解决方法,下面给出使用jsonp解决跨域的案例:

客户端的请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$.ajax({
url: URL,
type: "GET",
async: false,
data: requestParam,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "dataDeal",
success: function (message) {

},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("statusText:" + XMLHttpRequest.statusText + "\nstatus: " + XMLHttpRequest.status + ";\nreadyState: " + XMLHttpRequest.readyState +
";\ntextStatus: " + textStatus);
this;
}

服务端的接口处理

1
2
3
4
5
6
7
8
9
10
11
12
13
@RequestMapping("/doManage")
public void serviceForManage(HttpServletRequest httpServletRequest,
String callback,
HttpServletResponse httpServletResponse) {
try {
Writer out = httpServletResponse.getWriter();
ResponseEntity response = service();//service处理逻辑
log.info("callback = \n" + callback + "(" + response.toJsonString() + ")");
out.write(callback + "(" + JSONUtils.toJSONString(response) + ")");
} catch (Exception e) {
log.error("api error: " + e.getMessage());
}
}

在这里,client需要一个jsonp和jsonpcallback的两个参数,其中jsonp的参数callback对应于服务端的接口参数callback,而jsonpcallback的dataDeal对应于服务端接口中参数callback的值。