Using JSP code in JavaScript

后端 未结 7 1415
夕颜
夕颜 2020-12-09 05:14

I want to use JSTL\'s fmt tag in JavaScript to localize my alert messages. My JavaScript file is a standalone file and when I include fmt tag in js, the file browser gives J

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 05:59

    If your javascript is 'inline' with the rest of your JSP page, then simply use the technique suggested by Kees de Kooter.

    If your javascript needs to be in an external file (For sharing across pages, for example) then simply put it in its own JSP file.

    <%@page contentType="text/javascript" %>
    "
    "
    var someMessage = "${someMessage}"
    var anotherMessage = "${anotherMessage}"/>"
    

    And include it like this...

            
    

    You can then refer to 'someMessage' and 'anotherMessage' from within the file that includes the JSP, or from any javascript file that is included after 'yourScript.jsp.

    Note the use of the contentType attribute - 'text/javascript' prevents the JSP parser from complaining that the output isn't well formed XML - and that the tage refers to a JSP file.

    A combination of this technique and that suggested by @Magner should bring you to a sensible solution.

    EDIT: Changed the example to use 'text/javascript' insetad of 'text/plain' - thanks to @bobince for making me realise this error (Even though 'text/plain' works, it's more correct to use 'text/javascript'). Also, if the number of strings that need to be internationalised is small, and/or you can justify having your 'resources' in more than one place - one for the server side stuff and another for the client side stuff - @bobince's technique of using dynamic includes is a good one.

提交回复
热议问题