【问题标题】:Cannot retrieve json with ajax request from java/spring rest entry point无法从 java/spring rest 入口点检索带有 ajax 请求的 json
【发布时间】:2018-07-09 09:58:15
【问题描述】:

我有一个 REST 入口点嵌入到一个带有注释 @RestController 的类中:

@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

你知道为什么吗?是解析问题吗?

【问题讨论】:

    标签: javascript jquery ajax jsonp


    【解决方案1】:

    感谢这篇好帖子: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);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 2019-04-04
      • 2020-01-09
      • 2018-01-25
      • 2012-12-12
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多