问题
Hi my project is in struts 2. We have written common js files for client side validation. now the problem is that to implement internalization we have to change alert message as per the language. so my question is that is there any way to access resource property in js file. or any one suggest some alternative or example for the same.
回答1:
Store the alert messages in js files with file names like
alert_en.js alert_fr.js alert_jp.js
In each file store the alerts like this
var ALERT_EMAIL_INCORRECT = "Incorrect email";
var ALERT_USERNAME_INCORRECT = "Incorrect username";
Include file as per the user languages.
OR
You can load messages from the resource bundle using a JSP file and link in your page like this.
<script type="text/javascript" src="YOUR-FILE.JSP"></script>
In this JSP file you output JavaScript after reading from resource bundle.
Check this also.
回答2:
You can read properties file in js file using messageResource.js library created by me.
1) Include messageResource.js in your html.
<script src="messageResource.min.js"></script>
2) You can access key-value pair of properties file from js as follows.
// 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');
回答3:
You can write a JSON file with the native English language as key and L10N message as the value, and use AJAX to load the related JSON depending on user's browser language configuration, and alert the message with alert(tanslatedTable[USER_LANG][ENGLISH_STRING])
回答4:
I do this in my javascript within script tags on the jsp pages :
<code>
alert("<s:text name="amountMustBeNumeric"/>");
</code>
Works fine for me.
来源:https://stackoverflow.com/questions/11473705/accessing-resource-property-file-in-js-file