简体   繁体   中英

Grails 3.3.4 Simple Ajax Call

I'm attempting to save a record using an Ajax call in Grails 3.3.4. I've looked over other posts but none of them seem to have a resolve that has helped me.

The remote tags are deprecated in Grails 3, so that won't be any option. I also need to grab all my form fields, not individual text boxes. But it seems like my form data isn't getting passed through. Any ideas?

When I submit the form, I receive this error:

Error 500: Internal Server Error

URI /user/saveAjax

Class groovy.lang.MissingMethodException

Message null

Caused by No signature of method: com.vogella.grails.guestbook.$UserServiceImplementation.save() is applicable for argument types: (grails.web.servlet.mvc.GrailsParameterMap) values: [[controller:user, format:null, action:saveAjax]] Possible solutions: save(com.vogella.grails.guestbook.User), wait(), any(), wait(long), any(groovy.lang.Closure), isCase(java.lang.Object)

Domain

package com.vogella.grails.guestbook

class User {
    String name
    String last
    static constraints = {
    name (blank:false, nullable:false, size:3..30, matches:"[a-zA-Z1-9_]+")
    }

    String toString(){
        return name;
    }
}

Controller

package com.vogella.grails.guestbook

import grails.validation.ValidationException
import static org.springframework.http.HttpStatus.*

class UserController {

    UserService userService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    static scaffold = User

        def saveAjax(params) {
            render params
            userService.save(params)
            render "Success!"

        }
}

GSP

<!doctype html>
<html>
<head>
    <meta name="layout" content="main"/>
    <title>Welcome to Grails</title>

     <g:javascript library='jquery' />

</head>
<body>


<g:form id = "my_awesome_form">
<g:textField id = "box1" name="mytextbox"/>
<g:textField id = "box2" name="mytextbox2"/>
<input type="button" id = "mybutton" onclick="changeName()" value="create user"/>
</g:form>   
<div id="resultDiv"></div>     

<script>
function changeName()
    {   event.preventDefault();
        $.ajax({
            url:"<g:createLink url="[action:'saveAjax',controller:'User']" />",
            dataType: "json",
            type:"post",
            data: $('#my_awesome_form').serialize(),
            success: function() {
                    $( "#resultDiv" ).addClass( 'alert alert-info' ).append( 'Successfully saved event' )
            }, 
            error: function(xhr, status, error) {
                 $( "#resultDiv" ).addClass( 'alert alert-info' ).append(xhr.responseText);
            }
        });
    }
</script>

</body>
</html>

When trying to call params.box1 when passing the data by

$('#my_awesome_form').serialize();

I receive:

Caused by Ambiguous method overloading for method grails.artefact.controller.support.ResponseRenderer$Trait$Helper#render. Cannot resolve which method to invoke for [class com.vogella.grails.guestbook.UserController, null] due to overlapping prototypes between: [interface grails.artefact.controller.support.ResponseRenderer, interface java.lang.CharSequence] [interface grails.artefact.controller.support.ResponseRenderer, interface java.util.Map]

The error indicates you're passing a map params to the userService save method which expects a User object, you could either change the userService save method implementation so it accepts a map or just pass it on like this:

userService.save( new User( params ) )

This assumes the field ids in your form match the field names in your User domain so Grails is able to bind them , if not change them to match (much easier) or you'll have to manually set them like:

def user = new User()
user.name = params.box1
...

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