使用Ajax获取控制器值

时间:2014-07-05 22:47:06

标签: jquery ajax grails

我有一个允许用户发送邀请的Grails视图。调用视图时,我设置了变量

flash.invitation = [value from database]
。这将显示在视图中:

<h3>
<g:if test="${flash.numInvites > 1 || numInvites == 0}">
    You have ${flash.numInvites} invitations left
</g:if>
<g:else>
    You have ${flash.numInvites} invitation left
</g:else>
</h3>

我不想使用flash上​​下文变量,而是希望使用Ajax通过控制器函数从数据库中获取值。例如:

def numberOfInvitesAjax() {
    String inviteStr = "error: no session"
    User user = getSessionUser()
    if (user != null) {
        int invites = user.invitations
        inviteStr = Integer.toString(invites)
    }
    render "${inviteStr}"
}

我无法弄清楚如何在呈现页面时调用此函数,但是(我的JavaScript fu很弱)。

我在grails中尝试过remoteLink标记,但只有在有点击时才会获取值,但在呈现页面时则不会。我已尝试过remoteFunction,但这对我来说也不起作用。此外,这两个标记都标记为已弃用,以便将来从Grails中删除。

有关如何在呈现页面时使用grails获取值的任何指针?

1 个答案:

答案 0 :(得分:1)

您可以让控制器方法返回XMLJSON并在一次Ajax调用中使用JQuery获取它:

def numberOfInvitesAjax() {
    String inviteStr = "error: no session"
    User user = getSessionUser()
    if (user != null) {
        int invites = user.invitations
        inviteStr = Integer.toString(invites)
    }
    def model = [message: inviteStr]
    render model as JSON
}

要整理JavaScript代码,您可以在ApplicationResources.groovy

中创建模块
invitations {
  dependsOn 'jquery' //we need jquery to do the ajax calls
  resource url: 'js/invitations.js' //whatever structure you want 
}

在您的JS文件中,您可以使用将在您的页面中使用的方法创建Object Literal。要进行ajax调用,可以使用getJSON,例如:

var Invitations = {
  getNumberOfInvites : function(url) {
    $.getJSON(url, function(data){
      //append the message in the element with id inviteMessage
      $('#inviteMessage').html(data.message);
    });
  }
};

在您看来,您需要加载资源模块,并调用该函数,传递控制器操作的URL:

<!-- Load the javascript module -->
<head>
...
<r:require module="invitations" />
...
</head>
<body>
   ...
   <!-- we need this div to append the ajax message -->
   <div id='inviteMessage'></div>
   ...
   <!-- call functions when the page is ready -->
   <script type='text/javascript'>
     $(function(){
       Invitations.getNumberOfInvites('${g.createLink(action:"numberOfInvitesAjax")}');
     });
   </script>
</body>