2

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

Community
  • 1
  • 1
Daniel Gerber
  • 3,226
  • 3
  • 25
  • 32

2 Answers2

3

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

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • Thanks for your answer, but how can I do this with jersey? since I'm usually returning complex objects and let them be jsonified via moxy I cant just string concat the callback function. – Daniel Gerber Jan 31 '14 at 20:24
1

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

Daniel Gerber
  • 3,226
  • 3
  • 25
  • 32