2012-07-13 106 views
0

您好我的項目是在struts 2中。我們已經編寫了用於客戶端驗證的通用js文件。 現在的問題是要實現內部化,我們必須根據語言更改警報消息。 所以我的問題是,有什麼辦法可以訪問js文件中的資源屬性。 或任何一個建議一些替代或例子相同。訪問* .js文件中的資源屬性文件

回答

1

您可以編寫一個JSON文件,其中使用本地英語作爲鍵和L10N消息作爲值,並根據用戶的瀏覽器語言配置使用AJAX加載相關的JSON,並使用alert(tanslatedTable [USER_LANG] [ENGLISH_STRING])

+0

你能給我任何鏈接,我找到這樣的例子嗎? – Vipul 2012-07-13 17:04:24

+0

translatedTable = {「zh-CN」:{「hello」:「zh-CN hello zh-CN」},「ja」:{「hello」:「ja hello ja」}};當你想提醒「hello」消息時,只需alert(compiledTable [lang] [「hello」])即可。當然,你可以將它擴展到字符串的屬性,比如String.property.L10N()方法,然後以這種方式調用它:alert(「hello」.L10N()); – user1524017 2012-07-16 07:08:24

2

存儲與文件名的js文件的警告消息像

alert_en.js alert_fr.js alert_jp.js

在每個文件存儲警報這樣

var ALERT_EMAIL_INCORRECT = "Incorrect email"; 
var ALERT_USERNAME_INCORRECT = "Incorrect username"; 

按照用戶語言包含文件。

OR

您可以加載使用JSP文件和鏈接,在網頁這樣的資源包的消息。

<script type="text/javascript" src="YOUR-FILE.JSP"></script> 

在這個JSP文件中,您從資源包中讀取後輸出JavaScript。

檢查this也。我

<code> 
    alert("<s:text name="amountMustBeNumeric"/>"); 
</code> 

正常工作:

+1

這是一個很好的方法,但我肯定會鼓勵使用由JSP支持的操作,而不是直接使用JSP。這可以保留任何可能需要在視圖圖層外發生的處理。 – 2012-07-13 17:52:32

+0

是的,只從我的JS設計。不確定Java標準:) – kiranvj 2012-07-13 18:10:45

0

我這樣做是我的javascript腳本標記內的JSP頁面。

2

您可以使用我創建的messageResource.js庫讀取js文件中的屬性文件。

1)在你的html中包含messageResource.js。

<script src="messageResource.min.js"></script> 

2)您可以按如下方式從js訪問屬性文件的鍵值對。

// initialize messageResource.js with settings 
messageResource.init({ 
    // path to directory containing message resource files(.properties files), 
    // give empty string or discard this configuration if files are in the 
    // same directory as that of html file. 
    filePath : 'path/messageresource/' 
}); 

// will load the file 'path/messageresource/moduleName_en_US.properties' 
// and callbackFunction will be executed when loading is complete. 
messageResource.load('moduleName', callbackFunction, 'en_US'); 

// use messageResource.get function to get values from loaded file. 
var value = messageResource.get('key', 'moduleName', 'en_US');