Play Framework 2.3.x Ajax通信
JavascriptRoute生成
埋め込みルータ
- application.scalaにajaxCallを追加
Application.scala
/**
* This action is used to serve Home page of the application
*
* @return
*/
def index = Action { implicit request =>
Ok(views.html.index("Your new application is ready."))
}
/**
* This action is used to handle Ajax request
*
* @return
*/
def ajaxCall = Action { implicit request =>
Ok("Ajax Call!")
}
- conf/routesにajaxCallを追加
routes
GET /ajax-call controllers.Application.ajaxCall
- index.scala.htmlにRequestHeaderを追加
index.scala.html
@(message: String)(implicit req: RequestHeader)
@main("Welcome to Play") {
@message
}
- hello.jsにajaxCallを実装
hello.js
$(function() {
ajaxCall();
});
var ajaxCall = function() {
var ajaxCallBack = {
success : onSuccess,
error : onError
}
jsRoutes.controllers.Application.ajaxCall().ajax(ajaxCallBack);
};
var onSuccess = function(data) {
alert(data);
}
var onError = function(error) {
alert(error);
}
- 埋め込みルータは Scala テンプレート内で記述
main.scala.html
@(title: String)(content: Html)(implicit req: RequestHeader)
<!DOCTYPE html>
<html>
<head>
<title>@title</title>
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<!-- Embedded Javascript router -->
@helper.javascriptRouter("jsRoutes")(
routes.javascript.Application.index,
routes.javascript.Application.ajaxCall
)
<script src="@routes.Assets.at("javascripts/app.js")" type="text/javascript"></script>
</head>
<body>
@content
</body>
</html>
- 実行すると、ajax Callのアラートが表示されます。