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?.
And the call that I've made for getUsers with no arguments is working fine.
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 $.
function displayPopUp(stri) {
window.location = "@routes.UserController.deleteUser(stri)";
}
window.location = "@routes.UserController.getUsers()";
解决方案
In a short - it is not possible.
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":
function displayPopUp(stri) {
window.location = "@routes.UserController.deleteUser(stri)";
}
Solution
Javascript reverse routing:
Fast example:
create a javascriptRoutes action in a controller :
If you use Java:
public Result javascriptRoutes() {
return ok(JavaScriptReverseRouter.create(
"jsRoutes", routes.javascript.UserController.deleteUser()))
.as("text/javascript");
}
If you use Scala:
def javascriptRoutes = Action { implicit request =>
Ok(
JavaScriptReverseRouter("jsRoutes")(
routes.javascript.UserController.deleteUser
)
).as("text/javascript")
}
Add correponding route:
GET /javascriptRoutes controllers.Application.javascriptRoutes
Load the javascript routers:
Now you can use them in the client javascript
function displayPopUp(stri) {
window.location = jsRoutes.controllers.UserController.deleteUser(stri).url;
}