2012-05-07 20 views
0

可能重複:
How to use scriptlet inside javascriptJavascript和scriptlet:可以做到嗎?

<% 
if(request.getAttribute("exception")!=null){%> 

<script type="text/javascript" > 
    alert("hi"); 

    parent.error.document.open(); 
    parent.error.document.write("bye"); 
    parent.error.document.write(<%=request.getAttribute("exception").toString()%>); 
    parent.error.document.close(); 

</script> 
</form> 




<%}%> 

是否有可能有這種代碼?有其他選擇嗎?

+0

如果您使用scriptlet的某些[Tag Library](http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html),則可能會出現這種情況。 –

+0

您可以在scriplet條件下定義java腳本。 –

回答

0

你只是缺少一些引用來將該值視爲字符串而不是變量。

parent.error.document.write("<%=request.getAttribute("exception").toString()%>"); 

當打印到頁面,它會出現如下:

parent.error.document.write("myException"); 
+0

即使我沒有看到警告框顯示。 – abson

+0

@abson那麼你的'if'語句失敗了......你所擁有的是有效的代碼,除了上面的答案中提到的引號外。 –

+0

它將進入if塊但不打印或顯示警報框 – abson

0

您的代碼應該工作。但我更喜歡JSTL:

<c:if test="${not empty(exception)}"> 
    <script type="text/javascript"> 
     alert("hi"); 
     parent.error.document.open(); 
     parent.error.document.write("bye"); 
     parent.error.document.write(<%=request.getAttribute("exception").toString()%>); 
     parent.error.document.close(); 

    </script> 
</c:if> 

看起來更自然jsp。