10

I am making a web service that needs to return data in JSONP format. I am using the JSON taglib for JSP, and I thought all that had to be added were parenthesis, but I cannot find a good resource which verifies this.

For example, ever web service function returns using this function:

private static String getJSONPObject(String s) throws JSONException {
    return "(" + new JSONObject(s) + ")";
}

Is this correct?

Thanks!

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
Garrett
  • 11,451
  • 19
  • 85
  • 126

2 Answers2

23

JSONP is simply a hack to allow web apps to retrieve data across domains. It could be said that it violates the Same Origin Policy (SOP). The way it works is by using Javascript to insert a "script" element into your page. Therefore, you need a callback function. If you didn't have one, your Javascript would have no way to access the JSON object. But by using JSONP, your Javascript code can call the callback function.

So you must specify the callback name. So your function might look like this:

private static String getJSONPObject(String callback, String s) throws JSONException {
    return callback + "(" + new JSONObject(s) + ")";
}
JP Richardson
  • 38,609
  • 36
  • 119
  • 151
  • 2
    You should have access to the http request object or at least some way of accessing the callback which was sent, usually in this form: http://example.com?callback=name123 – Abdullah Jibaly Jan 13 '11 at 17:35
  • Ya, and to expand upon Abdullah's point, your Javascript code should then call the function "name123" to get the JSON. – JP Richardson Jan 13 '11 at 17:40
  • ah, thanks, i understand the callback now. however, i'm unsure as to how to retrieve it in the web service. i could ask for it as a parameter in my function, but that doesn't seem as user friendly as being able to parse it in the link as Abdullah exemplified. specifically, this is used inside a class, and the web service allows one to access these methods. can the request object be used inside the class? – Garrett Jan 13 '11 at 17:58
  • 1
    example.com?callback=name123 would call your JSP servlet which in turn calls the function "getJSONPObject" and passes "name123" as the "callback" parameter. – JP Richardson Jan 13 '11 at 18:03
2

I added one example to address Cross Domain JSONP ( Json with padding ) with Jquery and Servlet or JAX-WS webservice.

Please check this article.
http://reddymails.blogspot.com/2012/05/solving-cross-domain-problem-using.html

Reddymails
  • 793
  • 1
  • 10
  • 24