How to print a Struts2 ActionMessage in a JavaScript alert box

旧巷老猫 提交于 2019-12-19 11:54:15

问题


I have one Action class which is sending an action message using addActionMessage();.

I want to display that message in my JSP using a JavaScript alert box.

I've tried with

alert  ('<s:actionmessage/>');

but it is showing unterminated string literal.


回答1:


The <s:actionmessage/> tag generates an HTML like the following:

<ul class="actionMessage">
    <li>
        <span>
            Your Message 1
        </span>
    </li>
    <li>
        <span>
            Your Message 2, and so on...
        </span>
    </li>
</ul>

This will break your javascript function with invalid JS code:

alert('<ul class="actionMessage">
        <li>
      ... 
     ');

The solution is to manually iterate over your messages, and build the output by yourself, with <s:property/>, instead of using <s:actionmessage/>:

<s:if test="actionMessages!=null && actionMessages.size > 0">
    <script>
        var actionMessages;
        <s:iterator value="actionMessages" >
            // Iterate the messages, and build the JS String
            actionMessages += '-' + '<s:property />' + '\n';
        </s:iterator>        
        alert (actionMessages);
    </script>
</s:if>

Also remember to wrap the single quotes from your actionMessages.



来源:https://stackoverflow.com/questions/29788779/how-to-print-a-struts2-actionmessage-in-a-javascript-alert-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!