2016-10-19 49 views
0

當用戶登錄時,他們看到的第一個頁面是儀表板。在我的DashboardController中,我有一個靜態字符串。我想獲取該字符串值並將其分配給常用js文件中的變量。該常見的JavaScript文件包含在所有視圖頁面中。我怎樣才能做到這一點,而不使用<g:javascript>標籤?從常見的js文件訪問Grails控制器變量

回答

0

您可以使用Grails javascript標記。 http://docs.grails.org/3.1.1/ref/Tags/javascript.html

<g:javascript> 

    var myVariable = "${grailsVar}"; 

</g:javascript> 

如果您在別處使用JavaScript變量在JavaScript,請確保該變量之前使用變量在其他地方定義。

+0

的問題是我需要這個代碼在我common.js文件,而不是在一個gsp頁面。這個common.js文件包含在所有的gsp頁面中。 – oxyt

+0

我不知道有什麼方法將該代碼存入common.js文件。根據我的經驗,您在common.js文件之前聲明瞭前面提到的變量。然後你可以用你喜歡的任何方式在common.js文件中使用這裏聲明的變量。 – elixir

0

假設這是你的控制器。

class DashboardController() { 

//Action 
def dashboard() { 

     def dashboardData = "data which you access on dashboard page goes here" 

    return [data :dashboardData] 
    } 
} 

在你的GSP頁面接取數據變量是這樣的:

dashboar.gsp

<script> 

    var dashboard = ${data}; 

    console.log(dashboard);`` 

</script> 

感謝

+0

問題是我需要這個代碼在我的common.js文件中,而不是在gsp頁面中。這個common.js文件包含在所有的gsp頁面中 – oxyt

相關問題