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

时间:2015-07-29 09:45:15

标签: javascript jquery ajax grails

我是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')
}}

我希望你能帮助我。谢谢。

1 个答案:

答案 0 :(得分:1)

你可以用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 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>

尝试这个,如果有效让我知道......

快乐编码。