How do you pass a JavaScript variable to your Groovy controller?

橙三吉。 提交于 2020-01-14 02:53:31

问题


I have been searching on Google for a really good while, and I cannot find a solution to this problem. I am trying to access a JavaScript variable from my GSP file in my Groovy controller, but I can't find out how to do this.

Example:

//JavaScript stuff
<script>
    function validateForm(){
         var ret = false
    }
</script>

//Groovy controller stuff
def myAction = {
    println params.ret
}

How do I achieve something similar to this?


回答1:


Two ways to pass a variable to the controller:

  1. Ajax
  2. Form submit

Ajax

  • Use remoteFunction

    ${remoteFunction(controller: 'actionsController' , action: 'implementNewPixel', params: '\'ret=\' + ret')} 
    
  • Use Ajax

    var ret = false;
    jQuery.ajax({
        url: "${createLink(controller: 'actionsController', action: 'implementNewPixel')}",
        data: "ret=" + ret,
        success: function (data) {
            alert(data);
        }
    });
    

etc.

Form submit

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
    var ret;
    function validateForm(){
        ret = false;
    }

    jQuery(function () {
        jQuery("[name='jftForm']").submit(function () {
            jQuery("[name='ret']").val(ret);
        });
    });
</script>

<g:form name="jftForm" controller="actionsController" action="implementNewPixel">
    ...
    <g:hiddenField name="ret" value=""/>
    <g:submitButton name="submit" value="Submit"/>
</g:form>



回答2:


Look at the documentaton.

params: '\'ret=\' + ret'



来源:https://stackoverflow.com/questions/18093278/how-do-you-pass-a-javascript-variable-to-your-groovy-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!