如何在 JavaScript 警告框中打印 Struts2 ActionMessage

2022-01-16 00:00:00 javascript html jakarta-ee java struts2

我有一个 Action 类,它使用 addActionMessage(); 发送动作消息.

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

我想使用 JavaScript 警告框在我的 JSP 中显示该消息.

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

我试过了

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

但它显示的是未终止的字符串文字.

推荐答案

<s:actionmessage/> 标签 生成 HTML,如下所示:

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

这将使用无效的 JS 代码破坏您的 javascript 函数:

This will break your javascript function with invalid JS code:

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

解决方案是手动迭代您的消息,并自己构建输出,使用 <s:property/>,而不是使用 <s:actionmessage/>:

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 />' + '
';
        </s:iterator>        
        alert (actionMessages);
    </script>
</s:if>

还记得将 actionMessages 中的单引号括起来.

Also remember to wrap the single quotes from your actionMessages.

相关文章