2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Play Framework 2.3.x Ajax通信

Last updated at Posted at 2015-03-19

Play Framework 2.3.x Ajax通信

JavascriptRoute生成

埋め込みルータ

  1. 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のアラートが表示されます。

終わり

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?