如何从我的控制器grails调用js函数



我是grails新手,如果有人能帮助我就太好了。

我有一个js函数,我将调用在我的控制器打开一个弹出窗口后,在控制器中做一些事情。

我有gsp文件:

<g:form controller="admin" method="post">
<table summary="generer PDF">
..
..
<td>
<g:actionSubmit value="generate" action="genererAction"/>
</td>
</tr>
</table>
</g:form>

当用户点击"生成"(按钮)时,它必须调用这个函数:

def generateAction = {
def result
...
if (result){ 
//here, if result=true a popup will be displayed
}
else  {
redirect(action: 'index')
}}
我希望你能帮助我。谢谢你。

你可以用ajax来做,下面是一个例子:

视图:

<g:form controller="admin" method="post">
<table id="tableID" summary="generer PDF">
..
..
<td>
<!--<g:actionSubmit value="generate" action="genererAction"/>-->
<button onclick="preformAction(); return false;">generate</button>
</td>
</tr>
</table>
</g:form>

控制器:

def generateAction = {
def result
...
if (result){ 
//here, if result=true a popup will be displayed
render "success"
}
else  {
//redirect(action: 'index')
render "index"
}}

Script://复制这个脚本到你的视图

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function preformAction(){
    $.ajax({
        url:'${createLink(controller:"admin",action:"generateAction")}', // here you can pass the controller url
        data: {
            // data to be passed to controller
        },
        success : function(response){
            // this block is called after successful processing of controller
            // here you can call your js function after controller has finished its processing
            // consider response has 'success'
            if(response == 'success'){
                 OpenSAGPopup();
            } else if(response == 'index'){
                 window.location = '${createLink(controller:"admin",action:"index")}';
            }
        },
        error : function(response){
            // this block executes if any error occurs with the processing of controller
            alert("Error while generating pdf");
        },
    });
}
</script>

试试这个,如果它工作让我知道....

快乐编码。

最新更新