[英]accessing javascript through java in jsp
我的代碼目前看起來像這樣
<%
if (request != null) {
bustOut;
}
%>
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes");
}
</script>
如何調用Java代碼中的javascript函數? 或者那是不可能的?
JSP在webserver上運行,並在webbrowser請求時生成/生成HTML / CSS / JS代碼。 Web服務器將HTML / CSS / JS發送到webbrowser。 Webbrowser運行HTML / CSS / JS。 所以,你只需要讓JSP打印成字面為JS代碼。
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes");
}
<%
if (foo != null) {
out.print("bustOut();");
}
%>
</script>
或者, 更好的是 ,用EL
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes");
}
${not empty foo ? 'bustOut();' : ''}
</script>
(請注意,我將屬性名稱更改為foo
因為request
代表HttpServletRequest
,這可能會使其他人感到困惑,因為它永遠不會為null
)
無論哪種方式,當條件為真時,生成的HTML(您應該通過在瀏覽器中打開頁面,右鍵單擊它並選擇“ 查看源” )應該看起來像這樣:
<script language="javascript">
function bustOut(){
var newWin = window.open("the real url", "subWindow","height=500,width=700,resizable=yes,scrollbars=yes");
}
bustOut();
</script>
它現在打開你頭頂的燈泡嗎?
你不能從java調用javascript函數
您的Java代碼在服務器上執行,javascript - 在客戶端上執行。
您似乎需要有條件地打開文檔加載的新窗口。 為了那個原因:
<c:if test="${shouldDisplayWindow}">
$(document).ready(function() {
bustOut();
});
</c:if>
(這是用於檢測文檔加載的jQuery。你可以用純javascript替換它 - window.onload = function() {..}
或者document.onload = function() {..}
我認為)
請注意, request != null
是無意義的條件 - JSP中的請求永遠不會為null
。
最后 - 使用jstl標簽(就像我展示的那樣)而不是java代碼(scriptlets)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.