繁体   English   中英

如何从网页表单上的文本框中获取输入

[英]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>

请注意,在这种情况下,

  1. 不需要 g:form 标签的 controller 参数,按约定使用
  2. 根据您的路线(和 grails 版本),也可能会删除操作,但大多数情况下,这是您在表单中指定的内容,因此 grails 知道在哪里提交
  3. 参数稍微不同步“输入 A”->“输入 1”

然后在 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)
  }
}

但是,您应该只在管理区域或其他地方使用此技巧,因为需要考虑一些安全问题。

检查params map。

您可以通过名称访问字段:

def input1 = params.input1;
def input2 = params.input2

所以有一个提交按钮是有效的。

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM