Convert a javascript variable to scala in play fra

2019-07-20 17:34发布

问题:

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.