如何通过定期调用remoteFunction从控制器获取数据

How to get the data from the controller by periodically calling remoteFunction?

本文关键字:控制器 获取 数据 remoteFunction 调用 何通过      更新时间:2023-09-26

情况如下:

我有一个文件,每30秒更新一次信息。我创建了一个读取文件并提取所需数据的方法。在控制器中,比方说RefreshController,我有一个方法ref,每30秒调用一次:

def ref = {
    def Helper h = new Helper()
    def d = JSON.parse(h.readFile())
    render(view: 'index', model: [data: d])
}

通过grails remoteFunction:

<g:javascript>
setInterval(refreshMe, 30000);
function refreshMe(){
    ${remoteFunction(controller: 'refresh', action: 'ref', onSuccess: 'justDoIt(e);')}
}
function justDoIt(e){
    alert('hello'); // to create the table on the fly, but missing the data from the controller
}</g:javascript>

问题是,如何将刷新后的数据从控制器获取或访问到javascript函数中?我可以访问${data},但在这种情况下,我只获得控制器中data变量的第一个初始化值。

我想使用刷新的数据来动态创建一个表,而不是在现有的元素上。

如果有任何想法,我将不胜感激!

在您的控制器上,只需渲染json结果而不是视图,看看下面的示例,当您渲染视图时,您的数据对象将是您的视图。onSuccess也有数据参数。希望这能帮助

class RefreshController {
def index() { }
def ref () {
    println params
    def json = new JsonBuilder()
    json.state
    {
        name "Colorado"
        statehood 1876
        capital "Denver"
        majorCities "Denver", "Colorado Springs", "Fort Collins"
    }
    render json
}

}

视图:

    <!doctype html>
<%@ page import="com.package.example.*" %>
<html>
<head>
<title>Page Title</title>
 <meta name="layout" content="main"/>
<r:require modules="jquery"/>
<r:script>
   function refreshMe(){
    //alert("refresh js")
        ${remoteFunction(controller: 'refresh', action: 'ref', onSuccess: 'justDoIt(data,textStatus);')}
    }
    function justDoIt(data,textStatus){
        alert(responsData+" "+textStatus); 
    }
</r:script>
</head>
<body>
<a href="javascript:refreshMe();">Link text</a>
</body>
</html>

这是我的解决方案:

控制器:

import grails.converters.JSON
class RefreshController {
   def index = {}
   def ref= {
      def d = getString()
      render d as JSON
   }
   String getString(){
   // ...
   }
}

视图:

<html>
<head>
<title>Power In Use</title>
<meta name="layout" content="main" />
<g:javascript library="prototype"/>
</head>
<body>
<g:javascript >
  setInterval( "refreshMe();", 30000 );
  function refreshMe(){
      ${remoteFunction(action:'ref', controller:'refresh', onSuccess: 'makeTable(e)')}
  }
  function makeTable(e){    
  var d = e.responseText.evalJSON(true);
  // do something with data d
  }
</g:javascript>
</body>
</html>