JSONP与Jquery 1.9和Jersey 2.5.1

我已经google了很多,发现什么都不适合我的需求。 我在这里 , 这里和这里找到了这些类似的线程,但它们没有解决我的问题,或者我没有正确理解这一点。 我也读了几次jersey文件 。

我正在使用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说出了问题。

丹尼尔,非常感谢任何帮助

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

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

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

从服务中退回。

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

 @JSONP(queryParam = "callback") 

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

我在这里找到了解决方案! YEAH! 它实际上非常简单。 方法需要像这样声明:

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

并且ajax请求如下所示:

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

欢呼,丹尼尔