JSONP with Jquery 1.9 and Jersey 2.5.1

无人久伴 提交于 2019-12-10 23:19:44

问题


I've googled a lot and found nothing that suits my needs. I found these similar threads here, here and here, but they don't solve my problem or I don't understand this correctly. I also read the jersey documentation a couple of times.

I'm developing a server side application with jersey 2.5.1 and the client side with HTML/CSS/JavaScript. So for this worked out great, but no I'm stumbling. I'm using Media-Moxy as my Java2Json mapper.

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

If I now do a curl on the command line (see the accept header as request by jersey documentation)

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 does deliver the content as expected (in JSONP):

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

But if i call this with jquery like this:

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

I always get the error

 parsererror, Error: jQuery110207164248435292393_1391195897558 was not called 

I can see that the response in the browser contains the correct json and I get a 200 return code. But for some reason jQuery says that something is wrong.

Any help is kindly appreciated, Daniel


回答1:


callback([{ should have been ?([{ using the url you used with CURL.

The purpose of the callback parameter in the url is to specify the name of the callback function that should be executed. jQuery for example specified &callback=jQuery110207164248435292393_1391195897558 which should result in

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

being returned from the service.

You'll need to change this line in your server code:

@JSONP(queryParam = "callback")

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




回答2:


I found the solution here! YEAH! It's actually quite simple. Methods need to be declared like this:

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

and the ajax request looks like this:

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

cheers, daniel



来源:https://stackoverflow.com/questions/21488458/jsonp-with-jquery-1-9-and-jersey-2-5-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!