我有两个事件,我没弄错这里都执行了,也就是说,如果change
发生了,click
也被执行了。
作为其他选择,是否可以将<c:choose>...</c:choose>
用于多个事件?
谢谢!
<script>
$(document).ready(function () {
$('#idSelect').change(function (){
<c:set var="messjSelect" value="10" scope="session"/>;
<c:set var="messjRefresh" value="0" scope="session"/>;
});
});
</script>
<script>
$(document).ready(function () {
$('#refreshButton').click(function () {
<c:set var="messjRefresh" value="0" scope="session"/>;
<c:set var="messjSelect" value="0" scope="session"/>;
alert("do iT! ${messjSelect}");
});
});
</script>
答案 0 :(得分:1)
两者都执行,因为您将服务器端技术与前端技术混合在一起。
在服务器向客户端发送jsp文件之前,它会查找任何与Java相关的代码并运行它。这意味着您在jsp页面中拥有的JSTL / EL将在html / css / js之前运行。
为了澄清,您那里的<c:set
标签都可以运行,因为它是服务器端技术。如果您在javascript中将其指定为仅在单击之后运行,则没有关系。无论如何它将运行。 JSTL / EL和javascript不能以您认为的方式协同工作。
如何解决此问题?
一种可能的解决方案是将AJAX请求发送到Servlet。然后在该Servlet中处理会话变量,然后返回您想要的任何内容。例如:
<script>
$(document).ready(function () {
$('#idSelect').change(function (){
$.post("../SelectChangeServlet");
});
});
</script>
<script>
$(document).ready(function () {
$('#refreshButton').click(function () {
$.post("../RefreshButtonServlet", function(response) {
alert("do iT: "+ response);
});
});
});
</script>
SelectChangeServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = (request.getSession()); //get session
int messjSelect = 10;
int messjRefresh = 0;
session.setAttribute("messjRefresh", messjRefresh);
session.setAttribute("messjSelect", messjSelect);
System.out.println("You will see this text in IDE console when #idSelect is changed");
}
RefreshButtonServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = (request.getSession()); //get session
int messjSelect = 0;
int messjRefresh = 0;
session.setAttribute("messjRefresh", messjRefresh);
session.setAttribute("messjSelect", messjSelect);
System.out.println("You will see this text in IDE console when button is clicked");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8");
response.getWriter().write(Integer.toString(messjSelect)); //return messjSelect for alert (needs to be a string)
}
有关带有Servlet的Ajax的更多信息,请参见: How to use Servlets and Ajax?