在我的网络应用程序中发布表单时,我在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;
});
MessageSource控制器:
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
,但我无法理解。
也许你有一些很好的解决方案吗?
答案 0 :(得分:0)
也许这样?
<强> jsfile:强>
@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)