简体   繁体   中英

Grails command object validation with Ajax

In a Grails project I have a command object to validate submitted forms. This command obj. also has custom validators. The data is submitted with 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?

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.

Anyway, I guess you have a Comment domain class, and you expect to bind this entity from database. In this case, you should add a ".id" suffix to your parameter name.

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

PS: maybe you want to rename the "comment_id" to "comment" in your command class. Doing that, you will have to change the parameter name in your ajax request as "comment.id".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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