[英]How to get the input from a text box on a webpage form
這是在 Grails 上。 這是一個非常基本的事情,我顯然無法理解。
我的 index.gsp 中有這個
<g:form name="testForm" url="[controller:'test',action:'index']">
<g:textField name="Input A" value="${Input1}"> </g:textField>
<g:textField name="Input B" value="${Input2}"> </g:textField>
</g:form>
我的 TestController class 中也有這個:
class TestController {
def index = {
def Input1
def Input2
}
}
我想獲取用戶在網頁上輸入的兩個輸入,並將它們保存到 controller 上的相應字段(Input1、Input2)中。
我該怎么做 go 呢?
謝謝
你可以這樣寫你的表格:
<g:form name="testForm" controller="test" action="index">
<g:textField name="Input1" value="${Input1}"> </g:textField>
<g:textField name="Input2" value="${Input2}"> </g:textField>
<g:actionSubmit value="Send to controller" action="index"/>
</g:form>
請注意,在這種情況下,
然后在 controller
class TestController {
def index = {
def Input1 = params.Input1
def Input2 = params.Input2
["Input1": Input1, "Input2": Input2]
}
}
有了這個,值將被正確呈現(在返回的模型內)
您從隱式變量“ params
”接收表單參數。 在您的 controller 中執行log.error(params)
,您將知道它們是如何通過的。 您可以訪問您的參數,如params."Input 1"
。
請注意,有一些巧妙的方法可以處理來自一個 class 的多個輸入,例如給定域 class:
class Test {
String a;
String b;
}
你可以有一個表格:
<g:form name="testForm" controller="test" action="index">
<g:textField name="test.a" value="${Input1}"> </g:textField>
<g:textField name="test.b" value="${Input2}"> </g:textField>
</g:form>
在 controller 中,您可以:
class TestController {
def index = {
def testInstance = new Test(params.test)
}
}
但是,您應該只在管理區域或其他地方使用此技巧,因為需要考慮一些安全問題。
所以有一個提交按鈕是有效的。
<g:form name="testForm" controller="test" action="index">
<g:textField name="input1" value="${input1}"> </g:textField>
<g:textField name="input2" value="${input2}"> </g:textField>
<g:submitButton name="Submit" value="Submit"></g:submitButton>
</g:form>
...
class TestController {
def index = {
def Input1 = params.input1
def Input2 = params.input2
render(Input1+"<br />")
render(Input2+"<br />")
}
}
class TestController {
def index = {
def Input1 = params.input1
def Input2 = params.input2
render(Input1+"")
render(Input2+"")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.