我有这个代码
<%=out.write("<input
type=\"hidden\"
id=\"tid\"
value=\""+request.getParameter("id").toString()+"
\"/>")%>
<script type="text/javascript">
getPage(document.getElementById("tid").value)
</script>
此代码创建一个隐藏字段,其值来自
<site root>/viewPage.jsp?id=erwdf
url 并将此隐藏字段的值传递给 jsp 函数。当我在 Tomcat 上运行这段代码时,它给出了一个错误
The method print(boolean) in the type JspWriter is not applicable for the arguments (void)
在我上面给出的 JSP 代码行上。那么我做错了什么或者是否有任何替代方法将 GET 参数传递给 JavaScript 函数?对Javascript了解不多,刚开始学。
最佳答案
为什么隐藏字段如此复杂?
就这样
getPage('<%=request.getParameter("id")%>');
或者更简单,使用 EL
getPage('${param.id}');
你可能只想通过 Apache Commons Lang 转义特殊的 JS 字符StringEscapeUtils
,否则生成的 JS 代码可能会在参数值包含单引号或任何其他特殊 JS 字符时中断。
getPage('<%=StringEscapeUtils.escapeJavaScript(request.getParameter("id"))%>');
或者在 EL 中
getPage('${util:escapeJS(param.id)}');
另见:
关于javascript - 将 GET 参数传递给 JavaScript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9806266/