Search code examples
jqueryajaxjsonjsonpjersey-2.0

JSONP with Jquery 1.9 and Jersey 2.5.1


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


Solution

  • 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