简体   繁体   中英

Is it possible to execute a Grails dynamic finder query from JavaScript block

I am using Grails 2.5.2. I am trying to execute a dynamic finder query from JavaScript block with a variable. But the JS variable is not recognized. How can I do this?

My attempts as below:

$(".usrname").blur(function() {
        var username = $(this).val();
        var fullName = "${User.findByUsername(username)?.fullName}";
        alert(fullName);
    });

it won't work because it's rendered into html before your variable username value is known.

you have to use an action in your controller

def findUser() {
    def fullName = User.findByUsername(params.username)?.fullName
    return fullName
}

and then use ajax function in your gsp

$('.usrname').blur(function(){

    var username = $(this).val();
    var URL ="/yourController/findUser/?username=" + username;                                                                          

    $.ajax({
        url:URL,
        success: function(resp){
            alert(resp);
        }
    });
});

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