【问题标题】:Grails 2.5.0 - Command Object handle POST request with JSONGrails 2.5.0 - 命令对象使用 JSON 处理 POST 请求
【发布时间】:2015-09-27 18:39:51
【问题描述】:

我设置了一个表单来向 Grails 控制器发送 POST 请求,该控制器使用命令对象作为其一个参数。命令对象包含一些正确绑定的属性以及未正确绑定的项目列表。我正在做的是通常通过 POST 请求发送其他参数,但将列表包装为 JSON 字符串,因为我不确定通过 POST 发送列表的另一种方式(例如,XML 字符串) .让命令对象从字符串中正确绑定列表的最后一步是什么,或者有更好的方法将列表发送到命令对象?

编辑: 这是一个简化的版本:

测试 URI:

request.forwardURI = 'list1=[{"listprop1":"a","listprop2":"b"}]&prop1=c&prop2=d'

命令对象:

class MyListCommand {
    String listprop1
    String listprop2

    static constraints = {
        listprop1 nullable: true
        listprop2 nullable: true
    }
}

class MyCommand {
    List<MyListCommand> list1 = [].withLazyDefault {
        new MyListCommand('[]')
    }
    String prop1
    String prop2

    static constraints = {
        prop1 nullable: true
        prop2 nullable: true
    }
}

形式:

<form action="${createLink(action: 'myAction')}" method="post">
                <div ng-repeat="list1 in list1array">
                    <input type="hidden" name="list1[{{ $index }}].listprop1" value="{{list1.listprop1}}"/>
                    <input type="hidden" name="list1[{{ $index }}].listprop2" value="{{list1.listprop2}}"/>
                </div>
                <input name="prop1" type="text">
                <input name="prop2" type="text">
            </form>

【问题讨论】:

  • 您需要包含命令对象以及您的表单(或您如何组成您发布的数据),以便任何人就如何处理这个问题给您一个很好的答案。跨度>
  • 我添加了相关信息。我输入了 forwardURI(我从 Fiddler 简化了)。

标签: grails command-objects


【解决方案1】:

尝试像这样发送请求:

request.forwardURI = 'list1[0].listprop1=a&list1[0].listprop2=b&prop1=c&prop2=d'

更好

更好的方法是使用带有g:remoteForm 标签的Ajax。

【讨论】:

  • 当我在 Fiddler 中看到它时,表单将其编码为 list1%5B0%5D.listprop1=a&list1%5B0%5D.listprop2=b&prop1=c&prop2=d。那是问题吗?我收到错误“类 [class com.mypackage.MyCommand] 的属性 [list1] 不能为空”
  • 我添加了代码。请注意,AngularJS 正在填充 list1array。很抱歉,这个简化代码中的名称变得很时​​髦。
  • 啊,你没有使用&lt;g:form&gt;。由于您想使用 ajax,请尝试使用远程表单:grails.github.io/grails-doc/2.5.0/guide/…
  • 其实我不想用ajax。我只想正常通过邮寄提交表格。当我尝试
    时,我在 Fiddler 上得到了完全相同的结果。
  • 我最终按照你的建议使用了 AJAX 并让它以这种方式工作,如果你想把它作为一个单独的答案。
猜你喜欢
  • 2014-04-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 2020-08-01
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
相关资源
最近更新 更多