Convert a javascript variable to scala in play framework

[亡魂溺海] 提交于 2019-12-12 20:08:24

问题


I have some variables in javascript:

var something = 1;
var url = "@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?

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.


回答1:


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

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?

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

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

And in the JavaScript:

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

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



来源:https://stackoverflow.com/questions/48646563/convert-a-javascript-variable-to-scala-in-play-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!