簡體   English   中英

將值從Servlet傳遞到JSP中的onload JavaScript函數

[英]Pass values from Servlet to an onload JavaScript function in a JSP

我在Servlet中使用以下代碼來設置屬性ConfirmMsg

req.setAttribute("confirmMsg", "Update Values");

我要轉發給JSP

RequestDispatcher rd = req.getRequestDispatcher("displayDetails.jsp");
rd.forward(req, resp);

在我的JSP中,我需要在頁面加載時顯示消息。

<body onload = "showConfirmMsg();">

// .....

</body>

我應該在以下功能中做什么以顯示消息本身的負載?

function showConfirmMsg() {

// Code to show the alert box onload

}

使用jQuery,您可以執行以下操作:

<script>
$(function() {
    var msg = "${confirmMsg}";
    // do something with your message :)
});
</script>

<body onload="">不是很干凈:)

只需讓JSP / EL相應地打印JS代碼,以便瀏覽器檢索有效的HTML / JS代碼。

例如

<body onload="showConfirmMsg('${confirmMsg}');">

function showConfirmMsg(confirmMsg) {
    // ...
}

如果您不能保證${confirmMsg}不包含JS特殊字符(例如' ,換行符等),則需要事先通過Apache Commons Lang StringEscapeUtils#escapeJavaScript()

無需在加載時調用函數,而使用JSP scriplet。

<body>
<%=request.getAttribute("confirmMsg")%>
</body>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM