我有一个嵌入在带有注释@RestController
的类中的 REST 入口点:
@RequestMapping(value = "/test", method = RequestMethod.GET, produces="application/json")
public String getReitByDateRangeAdDoGeographic(){
return "{"msg":"success"}";
}
我尝试使用 ajax 请求请求它:
$.ajax({
dataType: "jsonp",
url: URL,
success: function(data) {
console.log("SUCCESS");
},
error: function (a,b, result) {
console.log("ERROR");
console.log(a);
console.log(b);
console.log(result);
}
});
当我在浏览器中查看 http 响应时,它是正确的:
{
"msg": "success"
}
但错误回调始终与消息一起调用(HTTP 代码为 200(:
14:19:00,855 Error: jQuery1113010493236335514322_1517318340103 was not called
Trace de la pile :
.error@http://localhost:63342/Sankey/external-lib/jquery/jquery-1.11.3.min.js:2:1809
b.converters["script json"]@http://localhost:63342/Sankey/external-lib/jquery/jquery-1.11.3.min.js:5:27779
Pb@http://localhost:63342/Sankey/external-lib/jquery/jquery-1.11.3.min.js:5:18379
x@http://localhost:63342/Sankey/external-lib/jquery/jquery-1.11.3.min.js:5:21793
.send/b.onreadystatechange@http://localhost:63342/Sankey/external-lib/jquery/jquery-1.11.3.min.js:5:27067
1 generateSankey.js:22:3
你知道为什么吗?是解析问题吗?
由于这篇不错的帖子找到了这个问题:http://www.baeldung.com/spring-jackson-jsonp。
这是由于"同源政策"。为了解决这个问题,我创建了类
@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
super("callback");
}
}
然后,ajax 请求如下所示:
$.ajax({
url: URL,
dataType: 'jsonp',
data: requestParam,
jsonpCallback: 'stringCallback',
success: function(data) {
console.log("SUCCESS");
console.log(data);
},
error: function (a,b, result) {
console.log("ERROR");
console.log(a);
console.log(b);
console.log(result);
}
});
function stringCallback(json){
console.log(json);
}