public static void index() {
List<Note> notes = Note.findAll();
if (request.params._contains("callback")) {
Gson gson = new Gson();
String out = gson.toJson(notes);
renderText(request.params.get("callback") + "(" + out + ")");
} else {
renderJSON(notes);
}
}
Is it possible to overwrite the renderJSON() method? If I do so Play recognizes this as a new action.
Thank you
Christian
Use the @Util annotation to prevent this behavior.
Is there a plan for implementing Jsonp in Play directly.
Christian
Not currently, but that's an interesting suggestion.
> --
> You received this message because you are subscribed to the Google Groups
> "play-framework" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/play-framework/-/NUGKqwe91B0J.
> To post to this group, send email to play-fr...@googlegroups.com.
> To unsubscribe from this group, send email to
> play-framewor...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/play-framework?hl=en.
>
--
Erwan Loisant
I you want to reuse it in several controllers, you can just create a
JsonP class and use the @With annotation to include it in any
controller.
> --
> You received this message because you are subscribed to the Google Groups
> "play-framework" group.
> To view this discussion on the web visit
> https://groups.google.com/d/msg/play-framework/-/onvkBK7MBBwJ.
package controllers;
import com.google.gson.Gson;
import play.mvc.*;
/**
* Enable JSONP for Play controllers
* @author ckoch
*
*/
public class Jsonp extends Controller {
/**
* renders a callback function if there
* is a request parameter callback
*
* @param o
*/
@Util
public static void renderJSON(Object o) {
if (request.params._contains("callback")) {
Gson gson = new Gson();
String out = gson.toJson(o);
renderText(request.params.get("callback") + "(" + out + ")");
} else {
renderJSON(o);
}
}
/**
* renders a callback function if there
* is a request parameter callback
*
* @param str
*/
@Util
public static void renderJSON(String str) {
if (request.params._contains("callback")) {
renderText(request.params.get("callback") + "(" + str + ")");
} else {
renderJSON(str);
}
}
}
Jsonp.renderJSON(…)
BTW, you should set the content-type to "text/javascript" when returning jsonp.
Jsonp.renderJSON(…)
BTW, you should set the content-type to "text/javascript" when returning jsonp.
Actually you don’t need it. Unless I’m mistaking, Erwan?
public static void renderJSON(String str) {
if (request.params._contains("callback")) {
renderText(request.params.get("callback") + "(" + str + ")");
} else {
Controller.renderJSON(str);
}
}