2012-01-30 26 views
1

這種情況:如何通過定期調用remoteFunction從控制器獲取數據?

我有一個文件信息每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

我想使用刷新的數據來創建一個表,而不是已經存在的元素。

我將不勝感激任何想法!

+0

在這裏回答 - http://stackoverflow.com/questions/5057266/grails-gremotelink-response – 2012-01-30 02:28:09

+0

@tomas謝謝你指出,但它沒有幫助。通過調用remoteFunction/remoteLink一次我沒有問題。我需要每30秒完成一次,我猜想,remoteFunction應該在javascript代碼中。然而,出於某種原因,我沒有得到任何'數據'參數。 – Agapij 2012-01-30 10:22:43

回答

1

在你的控制器上只顯示你的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> 
+0

謝謝阿里!事實上,你的想法最接近我找到的解決方案。我在下面提供。 – Agapij 2012-02-01 14:59:34

1

這裏是我的解決方案:

控制器:

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> 
相關問題