在Play框架中将JavaScript变量转换为Scala [英] Convert a javascript variable to scala in play framework

查看:82
本文介绍了在Play框架中将JavaScript变量转换为Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有一些变量:

I have some variables in javascript:

var something = 1;
var url = "@CSRF(routes.Some.thing(something))";

在编译过程中出现错误,因为某物" 没有引用javascript变量,换句话说,编译器无法识别它.是否有可能以某种方式转换/注入javascript变量?另外,这是否可以在javascript中实时工作,还是需要准备包含每个可能的某物"值的"@ CSRF(routes.Some.thing(something))" 数组?

I get an error during compilation because "something" does not refer to the javascript variable, in other words; the compiler can't identify it. Is it possible to convert/inject the javascript variable somehow? Also, does this work in real time in javascript or do I need to prepare an "@CSRF(routes.Some.thing(something))" array containing each possible "something" value?

应该在路由文件中看到一个简单的rest呼叫:

It's supposed to be a simple rest call, seen in routes file:

/something/:something controllers.Some.thing(something : Long)

一种替代方法是使用表格,但我想尽量不要使用.

An alternative would be to use a form, but I want to try not to.

推荐答案

您需要使用Javascript路由并将CSRF令牌添加到请求中.

You need to use a Javascript Routing and add the CSRF token to the request.

JavaScript漫游说明: https://www.playframework.com/documentation/2.6 .x/ScalaJavascriptRouting

Javascript Rounting description: https://www.playframework.com/documentation/2.6.x/ScalaJavascriptRouting

看看我对问题的回答,并解释如何将其用于资产(正确且长期的解决方案"),其他活动的用法相同:

Look at my answer to the question with explanation how to use it for assets("Correct and long solution"), the usage for other activities is the same: How to update src of a img from javascript in a play framework project?

因此,在您的情况下,JavaScript路由生成可能类似于:

So in your case, the Javascript routes generation can look like:

JavaScriptReverseRouter("jsRoutes")(
  routes.javascript.Some.thing
)

在JavaScript中:

And in the JavaScript:

var something = 1;
var url = jsRoutes.controllers.Some.thing(something).url;

最后一个-不要忘记在请求中添加Csrf-Token标头.

The last - do not forget to add Csrf-Token header to the request.

这篇关于在Play框架中将JavaScript变量转换为Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆