1

在我的 Web 应用程序中发布表单时,我在 javascript 中执行了几次检查,然后在后端验证表单。js 验证依赖于 I18 消息和图像。如果这是一个 scala 模板,我当然会使用@Messages@routes.Assets.at但我不想混合使用这两者(scala 模板和 .js 文件)。

例如,我在我的 js 文件中进行了此检查,其中当前图像路由是硬编码的:

$("form input[type=submit]").click(function (e) {

            e.preventDefault();
            var email = $("#username");
            var emailPattern = /^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;

            if (email.val() == "") {
                email.css("background-image", "url('/assets/images/general/input-row-red.jpg')");
                return e.preventDefault();
            } else {
                email.css("background-image", "url(/images/general/inputTextBg.png)");
            }
    });

我试图用他们需要的消息来准备 js 文件,如下所示:

.js 文件:

/* Prepare messages*/
var messages = "";

$.getJSON("/messages/source", {
        "keys": "sms.form.login.hide,sms.form.login"},
    function (data) {
        messages = data.messages;
    });

消息源控制器:

object MessageSource extends Controller {

  def getMessages(keys : String) = Action { request =>
     if(keys.isEmpty) {
       BadRequest(Json.obj("status" -> "KO", "message" -> "key plix!"))
     }
     else {
       var js = Map.empty[String, String]
       for (k <- keys.split(",")) {
         js = js + (k -> Messages(k))
       }
       Ok(Json.obj("status" -> "OK", "messages" -> js))
     }
  }
}

但我不觉得这是最好的解决方案。我看过,http://www.playframework.com/documentation/2.1.0/ScalaRouting但我无法弄清楚。也许您对我有一些不错的解决方案?

4

1 回答 1

0

也许这样?

js文件:

@scripts = {
        <script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>
        <script type="text/javascript">
        jsRoutes.controllers.Application.messages("admin.venue.1,admin.venue.2,admin.venue.3" ).ajax({
            type: 'GET',
            success: function (data) {
                console.log(data.messages);

        },
            error: function () {
                console.log("error");
            }
        });
        </script>    
    }

控制器:

object Application extends Controller {

  def javascriptRoutes = Action {
    implicit request =>
      import routes.javascript._
      Ok(
        Routes.javascriptRouter("jsRoutes")
          (
            routes.javascript.Application.messages
          )
      ).as("text/javascript")


  }

  def messages(keys : String) = Action {
    implicit request => {
      val messages = keys.split(",").map { key =>
        key -> Messages(key)
      }.toMap

      Ok(Json.obj("status" -> "OK", "messages" -> messages))
    }
  }

}

路线:

# Javascript routes
GET         /javascriptRoutes                 controllers.Application.javascriptRoutes
GET         /messages                       controllers.Application.messages(keys: String)
于 2013-12-11T14:22:42.037 回答