如何使用Java脚本window.location将参数传递给Play框架中的Java方法? [英] How to pass arguments using java script window.location to a java method in play framework?
问题描述
我想使用javascript中的window.location在Java文件中调用带有参数的方法.我尝试了不同的方法,但无法调用该函数.当我尝试打印所传递的值时,它会记录在控制台中,但是当我尝试在方法中调用它时,它会抛出未找到值"错误.我应该对代码进行什么更改以调用该方法?.
I want to call a method with parameter in my java file using window.location in javascript. I've tried different approaches but not able to call the function. When I tried to print the value that I've passed it is getting logged in the console but when I tried to call it in the method it is throwing value not found error. What changes I should make to my code to call the method?.
我为不带参数的getUsers进行的调用工作正常.
And the call that I've made for getUsers with no arguments is working fine.
对于使用参数进行调用,我尝试将其作为一个单独的字符串,并尝试连接并分配给window.location,即使它没有用.我想在控制器中成功调用该方法.
And for calling with arguments I tried to take it as a separate string and tried to concat and then assign to window.location even then it hasn't worked. I want to successfully call the method in my controller.
尝试使用单引号@和$.
Tried with single quotes, @ and $.
<script>
function displayPopUp(stri) {
window.location = "@routes.UserController.deleteUser(stri)";
}
window.location = "@routes.UserController.getUsers()";
</script>
推荐答案
简而言之-这是不可能的.
In a short - it is not possible.
@routes.UserController.deleteUser(stri)
是在服务器上编译的,而function displayPopUp(stri)
是在客户端上运行的,因此下一个代码将无法按预期"工作:
The @routes.UserController.deleteUser(stri)
is compiled on the server, and function displayPopUp(stri)
is run on the client, so the next code will not work "as expected":
<script>
function displayPopUp(stri) {
window.location = "@routes.UserController.deleteUser(stri)";
}
</script>
解决方案
JavaScript反向路由:
Javascript reverse routing:
https://www.playframework.com/documentation/2.6.x/JavaJavascriptRouter https://www.playframework.com/documentation/2.6.x/ScalaJavascriptRouting
快速示例:
在控制器中创建javascriptRoutes 操作:
create a javascriptRoutes action in a controller :
如果您使用 Java :
public Result javascriptRoutes() {
return ok(JavaScriptReverseRouter.create(
"jsRoutes", routes.javascript.UserController.deleteUser()))
.as("text/javascript");
}
如果您使用 Scala :
def javascriptRoutes = Action { implicit request =>
Ok(
JavaScriptReverseRouter("jsRoutes")(
routes.javascript.UserController.deleteUser
)
).as("text/javascript")
}
添加相应的路线:
GET /javascriptRoutes controllers.Application.javascriptRoutes
加载 javascript 路由器:
<script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>
现在,您可以在客户端 javascript
Now you can use them in the client javascript
<script>
function displayPopUp(stri) {
window.location = jsRoutes.controllers.UserController.deleteUser(stri).url;
}
</script>
这篇关于如何使用Java脚本window.location将参数传递给Play框架中的Java方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!