public
Last active

Using JS routes in Playframework 2.x (Scala)

  • Download Gist
MyController.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
package controllers
 
object MyController extends Controller {
 
def add() = Action { implicit request =>
Form( tuple ( "user" -> number ) ).bindFromRequest.fold(
errors => BadRequest,
t => {
Ok("Add id: " + t)
}
)
}
 
 
def delete(input : String) = Action { implicit request =>
try {
val id = java.lang.Long.parseLong(input)
Ok("Delete id: " + id)
} catch { case _ : Throwable => BadRequest }
}
 
}
routes
1 2 3 4 5 6 7 8 9
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
 
# ... Normal routes
 
# JS Routes:
PUT /comment/add controllers.MyController.add
DELETE /comment/:id controllers.MyController.delete(id)
template.scala.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
@(id : Int)
 
@helper.javascriptRouter("myRoutes")(
routes.javascript.MyController.add,
routes.javascript.MyController.delete
)
 
<script type="text/javascript">
function addSomeAjax() {
myRoutes.controllers.MyController.add().ajax({
data: { user: @id },
success: function(data) {
alert("Succes!111one");
}
})
}
function deleteSomeAjax() {
myRoutes.controllers.MyController.delete(@id).ajax({
success: function(data) {
alert(data);
}
});
}
</script>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.