1

我正在尝试根据文本框的内容将动态值发送到 Routes URI 路径,但是当我尝试时,它以 null 的形式出现。

这是我尝试过的:

<form action="@{Application.hello(myName)}" method="get">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>

我希望将文本框中输入的值传递给路由文件,但它不起作用。如果我传递一个常量字符串,例如:

<form action="@{Application.hello('John')}" method="get">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>

然后我的代码工作正常,但我不想要一个常数值;我希望在路由 URI 路径中传递文本框值。

编辑

使用上面的代码,每次单击按钮并提交表单时,URL 都会包含名称,/.../John因为我已经对其进行了硬编码。

我想要实现的不是将名称硬编码为John. URL 中的名称将来自用户在文本框中输入的内容。例如,如果用户输入的名称是,Mike那么 URL 应该是/.../Mike基于用户文本框输入的等等。

简而言之,我不想将值硬编码为John但愿意根据文本框输入使其动态化。

请让我知道如何做到这一点。

问候,

4

1 回答 1

1

您正在尝试路由到尚未指定的用户名的 URL。

在页面加载时,当用户没有将 John 指定为名称时,Play 不知道您想要 hello /name/John。

为了让您做您想做的事情,您需要使用 javascript 在提交时更改表单操作 url 以将操作 url 替换为/name/(value of myName input field)

或者,您可以将其拆分为两个单独的控制器操作。

路线:

POST /greet  Application.greet
GET  /users/{myName}  Application.hello

应用程序.java

// accepts the form request with the myName paramater
public static void greet(String myName) {
    // redirects the user to /users/{myName}
    Application.hello(myName);
}

// welcomes the user by name
public static void hello(String myName) {
    render(myName);
}

查看模板:

<-- this url should be /greet  (noted we are submitting via POST) -->
<form action="@{Application.greet()}" method="post">
Name: <input type="text" name="myName">
<input type="submit" value="Submit">
</form>
于 2013-02-02T18:51:23.033 回答