问题
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:
- Ajax
- 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