简体   繁体   中英

Use spring:message from JavaScript

I have a JQuery function who add a Table in the JSP dynamically:

$('#add').click(function(event) {

    event.preventDefault();

$('.tabela_procurador').before
    ('<table id="tabela_nova' + i + '" class="tabela_nova"> ' +
        '<tr> ' +
            '<td colspan="4" class="subTitulo_barra"> ' +
            '<spring:message code="representante_legal" /> '+ i +' ' +
            '</td> ' +
        '</tr> ' +
      '</table>');
     i++
   });
});

But when i added this table i lost the spring:message.

There is something i can do to jquery recognize this spring:message?

As a workaround, put the message value in a hidden input on your jsp page. Then get its value in your javascript. In your case:

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

In your javascript (using jquery) you can then use it as follows:

$('#representante_legal').val()

There's no way for jQuery to have access to a spring tag. spring:message is processed server-side before the page is sent to the client, javascript/jQuery is processed later on the client side.

Make sure <spring:message code="representante_legal" /> is in a JSP, if that tag is in a javascript file, it will never be translated to the localized string.

JSP files are compiled before they are sent to the requesting client, while javascript is served as static content.

In your JSP, you can assign the spring:message to a javascript variable, making available to your other jQuery code:

# In .JSP
<script type="text/javascript">
  var abc="<spring:message code="representante_legal"/>";
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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