boolean isAjax() {
return "XMLHttpRequest".equals(Http.Context.current().request().getHeader("X-Requested-With"));
}
boolean isJsonp() {
return "true".equals(Http.Context.current().request().getQueryString("jsonp"));
}
@BodyParser.Of(BodyParser.Text.class)
public static Result channelIndex(Long channelId) {
if (isJsonp()) {
// return jsonp
} else {
// return html
}
}
Hello,
I would like to be able to differentiate an ajax request over a full page request from the browser. For that reason, I have setup my ajax code to request all resources over the /ajax/ suffix. So if I have example.com/channels/1234, when fetching the same page over ajax, I would request example.com/ajax/channels/1234. How would I go about doing this?
1. Setup routes for each endpoint - One normal and one for ajax and set a default parameter. like this:
GET /channels/:channel controllers.Channels.channelIndex(channel: Long, isAjax="false")
GET /ajax/channels/:channel controllers.Channels.channelIndex(channel: Long, isAjax="true")
2. Have a base Controller that checks if the url starts with "/ajax/" and set an instance variable isAjax to True or False. Then the controller renders a complete HTML page if isAjax is false else render a JSONP.
I would prefer to go with 2 as that makes it more generic and maintainable than having lots of routes. Could someone point out as to how I could achieve this ?
My frontend interacts over a JsonPish interface, this is my sample controller code
@BodyParser.Of(BodyParser.Text.class)
public static Result channelIndex(Long channelId, String isAjax) {
String content = channel.render(
Channel.findById(channelId)
).body();
ObjectNode result = Json.newObject();
result.put("status", "OK");
result.put("message", content);
return ok("$$.foo(" + result + ")");
}
PS: I come from a python background. I will need some guidance to get things started.
--
Abhi
--