Some of my Play Framework views will accept normal request (GET via a link) and ajax request (called from a javascript code if the user have js enabled).
My actual problem is that my code looks for the two possibil开发者_如何学编程ities in the same method, something like this :
public static void lostPassword() {
HashMap<String, Object> ajax = new HashMap<String, Object>();
validation.clear();
validation.required("email", params.get("email"));
validation.email("email", params.get("email"));
if (!validation.hasErrors()) {
Account account = Account.findAccount(params.get("email"));
if (account != null) {
// Send the email:
Mails.lostPassword(account);
if (request.isAjax()) {
ajax.put("success", true);
renderJSON(ajax);
}
else {
renderTemplate("account/password/sent.html");
}
}
validation.addError("email", "This email does not exists."); // TRANS
}
if (request.isAjax()) {
ajax.put("success", false);
ajax.put("validation", AjaxUtils.fromValidationErrorsToAjax(validation.errors()));
renderJSON(ajax);
}
else {
validation.keep();
renderArgs.put("email", params.get("email"));
renderTemplate("account/password/form.html");
}
}
As you can see, I check for which type of request is made for returning a proper response, and I'm sure it's not the best way to do it.
But how would you do?
I thought about making a private method that would do the work and return a boolean, but what happens for the Validation object? And does that mean I would have to make two other methods, one for the HTML request, an other for the AJAX request?
How do you do?
Thanks for your help!
You are better off using content types. It allows you to use a single controller, and have multiple Temaplates, for outputting in a variety of formats. In my book, I used a standard HTML page, and an RSS page as two view over the same controller action and associated model data.
The Play documentation does a good job of explaining how to use it. http://www.playframework.org/documentation/1.2.3/routes#content-types
Basically, you can do it programatically or in your routes file, or by allowing play to figure it out by the content type by the Http request type. The later is set in your ajax request by specifically setting up JSON as the content type. This should be straightforward, especially if you are using jquery for your Ajax requests.
精彩评论