简体   繁体   English

通过js从Spring资源包中获取消息

[英]Get message from spring resource bundle by js

Normally I retrieve i18n messages via <spring:message code="" /> tag in jsp. 通常,我通过jsp中的<spring:message code="" />标记检索i18n消息。 But as response of ajax query I get message code in i18n property file. 但是作为ajax查询的响应,我在i18n属性文件中获得了消息代码。 How can I get message by this code via JS? 如何通过JS通过此代码获取消息?

There is no "normal" way to get messages from JS, but you have two solutions: 没有从JS获取消息的“常规”方法,但是您有两种解决方案:

First solution: by an Ajax call. 第一个解决方案:通过Ajax调用。

Second solution : Send you're value at the loading of the page in hidden input html 第二种解决方案:在加载页面时使用隐藏的输入html发送您的价值

<c:set var="val"><spring:message code="username"/></c:set>
<input id="username" type="hidden" value="${val}"/>

In your javascript (using jquery) you can then use it as follows: 然后,在您的JavaScript(使用jquery)中,您可以按以下方式使用它:

$('#username').val()

You can inject MessageSource to your controller and return a String message from that controller. 您可以将MessageSource注入控制器,并从该控制器返回String消息。 Simply: 只是:

@Autowired
MessageSource messageSource;

@RequestMapping(value="/myajax", method=RequestMethod.GET)
@ResponseBody
public String getMyAjaxMessage() {
    return messageSource.getMessage(..); // use your proper arguments or extract from request parameters

}

javascript (assuming jquery is used): javascript(假设使用了jquery):

$.get('/myajax', function(data){
    // do whatever you want with data (will contain your message)
});

Here are docs: 这里是文档:

MessageSource 讯息来源

jquery get jQuery获取

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM