2010-12-04 53 views
5

是否有任何方法將參數傳遞給由GWT生成的.nocache.js腳本文件並在onModuleLoad函數中對它們進行評估?像這樣:將參數傳遞給GWT引導.nocache.js腳本

<script type="text/javascript" src="application/Application.nocache.js?appId=461333815262909"></script> 

主頁URL應該從GWT裏面的東西的工作,所以傳遞的appid參數作爲主機頁面的查詢參數,並與Window.Location.getParameter訪問它完全分開是不是選項。我知道我可以隱藏這些參數,例如在隱藏的DIV中,然後從腳本中查詢它們,但如果可能的話,我希望避免主機頁面中的任何進一步依賴。

謝謝! Lisa

回答

2

不,但this article可能有助於將參數從服務器傳遞到客戶端腳本,以便在頁面加載時進行評估。

2

有似乎是在GWT的,沒有原生支持,但我想出了以下解決方案最近:

假設你的腳本始終遵循的命名約定「/<moduleName>.nocache.js」,您可以獲取所有<script>元素主機頁面並在src屬性中搜索引用此內容的頁面。然後您可以從那裏拉取URL編碼的屬性。

這是我的示例實現,打算用GWT.getModuleName()作爲第一個參數調用。

/** 
* Fetches a parameter passed to the module's nocache script. 
* 
* @param moduleName the module's name. 
* @param parameterName the name of the parameter to fetch. 
* @return the value of the parameter, or <code>null</code> if it was not 
* found. 
*/ 
public static native String getParameter(String moduleName, String parameterName) /*-{ 
    var search = "/" + moduleName + ".nocache.js"; 
    var scripts = $doc.getElementsByTagName("script"); 
    for(var i = 0; i < scripts.length; ++i) { 
     if(scripts[ i ].src != null && scripts[ i ].src.indexOf(search) != -1) { 
      var parameters = scripts[ i ].src.match(/\w+=\w+/g); 
      for(var j = 0; j < parameters.length; ++j) { 
       var keyvalue = parameters[ j ].split("="); 
       if(keyvalue.length == 2 && keyvalue[ 0 ] == parameterName) { 
        return unescape(keyvalue[ 1 ]); 
       } 
      } 
     } 
    } 
    return null; 
}-*/; 

歡迎提出改進建議。

3

而不是隱藏信息隱藏divs可能會變得混亂,一個簡單的方法來傳遞參數是通過HTML元標記。

在調用GWT腳本的HTML頁面,添加一個meta標籤如下:

<html> 
    <head> 
    <meta name="appId" content="461333815262909"> 
    ... 

然後,在你的模塊的入口點,如下解析它:

@Override 
public void onModuleLoad() { 
    NodeList<Element> metas = Document.get().getElementsByTagName("meta"); 
    for (int i=0; i<metas.getLength(); i++) { 
     MetaElement meta = (MetaElement) metas.getItem(i); 
     if ("appId".equals(meta.getName())) { 
      Window.alert("Module loaded with appId: " + meta.getContent()); 
     } 
    } 
} 

當然,它不像在腳本標籤的src URL中傳遞參數那麼簡單,但我相信它比在文檔內容中隱藏div更簡單,並且比人工重新解析腳本標籤的源屬性更少出錯。