【问题标题】:JSONP with Jquery 1.9 and Jersey 2.5.1JSONP 与 Jquery 1.9 和 Jersey 2.5.1
【发布时间】:2014-02-24 15:25:44
【问题描述】:

我用谷歌搜索了很多,没有找到适合我需要的东西。我发现了这些类似的线程hereherehere,但它们并没有解决我的问题,或者我没有正确理解这一点。我还阅读了几次jersey documentation

我正在使用 jersey 2.5.1 开发服务器端应用程序,并使用 HTML/CSS/JavaScript 开发客户端应用程序。所以这个效果很好,但不是我绊倒了。 我使用 Media-Moxy 作为我的 Java2Json 映射器。

@GET
@JSONP
@Path("search")
@Produces({MediaType.APPLICATION_JSON, "application/javascript"})
public String findByTagsAndBoundingBox(@QueryParam("topLeftLat") Double topLat...) {
    // do some work
    return json.toString();
}

如果我现在在命令行上执行 curl(请参阅接受标头作为球衣文档的请求)

curl -X GET -H "Accept: application/javascript" "http://localhost:8181/xxxxx/xxxx/search?topLeftLat=59.93704238758132&topLeftLon=10.68643569946289&bottomRightLat=59.890573111743336&bottomRightLon=10.806941986083984&tag=Restaurant&callback=?"

Jersey 确实按预期交付了内容(在 JSONP 中):

callback([{"id":3134,"lon" .... }])

但是如果我像这样用 jquery 调用它:

$.getJSON("http://localhost:8181/xxxx/yyyy/search?" + query + "&callback=?", function() {
     console.log( "success" );
})

我总是得到错误

 parsererror, Error: jQuery110207164248435292393_1391195897558 was not called 

我可以看到浏览器中的响应包含正确的 json,并且我得到了 200 返回码。但是由于某种原因,jQuery 说有问题。

感谢您的帮助, 丹尼尔

【问题讨论】:

    标签: jquery ajax json jsonp jersey-2.0


    【解决方案1】:

    我找到了解决方案here!是的! 其实很简单。方法需要这样声明:

    @JSONP(queryParam="callback")
    @Produces({"application/x-javascript"})
    public TestResult getAllTestData(@QueryParam("callback") String callback) 
    

    ajax 请求如下所示:

    $.getJSON(serviceURL + 'get?callback=?', function(data) { ...
    

    干杯, 丹尼尔

    【讨论】:

    【解决方案2】:

    callback([{ 应该是 ?([{ 使用与 CURL 一起使用的 url。

    url中callback参数的作用是指定应该执行的回调函数的名称。例如,jQuery 指定了 &callback=jQuery110207164248435292393_1391195897558,这应该会导致

    jQuery110207164248435292393_1391195897558([{"id":3134,"lon" .... }])
    

    从服务中返回。

    您需要在服务器代码中更改此行:

    @JSONP(queryParam = "callback")
    

    参考:https://jersey.java.net/documentation/latest/user-guide.html#d0e7040

    【讨论】:

    • 感谢您的回答,但是我该如何使用球衣呢?因为我通常会返回复杂的对象并让它们通过 moxy 进行 jsonified 我不能只是字符串连接回调函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多