为什么我的onclick只会执行一次?

hpygzhx520 2017-04-14 10:06:09
各位朋友,winform多年,现在在照葫芦画瓢的阶段学JAVA-WEB。现有一个问题很困惑:
产生一个图片验证码,然后想点一下换一个图片。图片由一个servlet产生,代码从网上搬来的。每次刷新都能生成新的图片,但是,但是,单击的话,只会变化一次。也就是说,点击第二次就没任何反应了。刷新之后又能点击一次……
JSP片段如下:
<body>
This is my JSP page. <br>
<img id="img" name="image" src="authImageServlet"
onclick="document.all.image.src='authImageServlet?Math.random()'">
</body>
其中authImageServlet用于生成图片:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");

//生成随机字串 
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);//与这个问题无关
//存入会话session 
HttpSession session = request.getSession();
//删除以前的
session.removeAttribute("verCode");
session.setAttribute("verCode", verifyCode.toLowerCase());
//生成图片 
int w = 100, h = 30;
VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);//与这个问题无关
System.out.println(verifyCode);//验证码没变化的时候这里的确没执行
}

还没入门,特来请教。谢谢各位。
...全文
948 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
hpygzhx520 2017-04-14
  • 打赏
  • 举报
回复
非常感谢。我估计是因为我自己不熟悉WEB编程而哪里写得不对。这种实现方式 之前试过的,但没写好,效果不对。 你的代码没问题!感谢!
李德胜1995 2017-04-14
  • 打赏
  • 举报
回复
改成这样就可以了。。。。

<script type="text/javascript">
function change(){
	var img= document.getElementById("img");
	img.src = "${pageContext.request.contextPath}/authImageServlet?timestamp="+new Date().getTime();
}
</script>
<img id="img" onclick="change()" src="authImageServlet">

81,122

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧