简体   繁体   English

使用Ajax进行Grails命令对象验证

[英]Grails command object validation with Ajax

In a Grails project I have a command object to validate submitted forms. 在Grails项目中,我有一个命令对象来验证提交的表单。 This command obj. 此命令obj。 also has custom validators. 也有自定义验证器。 The data is submitted with jQuery ajax ($.post). 数据使用jQuery ajax($ .post)提交。

My question is how can I now map the data send with jQuery Ajax to the properties listed in the Command object? 我的问题是我现在如何将使用jQuery Ajax发送的数据映射到Command对象中列出的属性?

For example: 例如:

$.post('comment/save', {id: id, title: title});

and then in the controller: 然后在控制器中:

def save(saveCommand cmd){

  if (!cmd.validate()){
    ...
  }
}

class saveCommand {

   Comment comment_id    // maps to: params.comment_id send with ajax
   String title          // maps to: params.title send with ajax

   // constraints
   // validators    
}

The comment_id attribute should be bound from a "comment_id" parameter in the parameter map you sent from jQuery, not as "id" as you have right now. comment_id属性应该与从jQuery发送的参数映射中的“ comment_id”参数绑定,而不是像现在一样作为“ id”绑定。

Anyway, I guess you have a Comment domain class, and you expect to bind this entity from database. 无论如何,我猜您有一个Comment域类,并且您希望从数据库绑定该实体。 In this case, you should add a ".id" suffix to your parameter name. 在这种情况下,应在参数名称中添加“ .id”后缀。

$.post('comment/save', {"comment_id.id": id, "title": title});

PS: maybe you want to rename the "comment_id" to "comment" in your command class. PS:也许您想在命令类中将“ comment_id”重命名为“ comment”。 Doing that, you will have to change the parameter name in your ajax request as "comment.id". 这样做,您将必须在ajax请求中将参数名称更改为“ comment.id”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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