更改img标签中的src属性值,但是浏览器中的图片并没有更新

来源:互联网 发布:网络时间校对器 编辑:程序博客网 时间:2024/05/19 10:34

问题产生如题,原先代码如下:

<!DOCTYPE html> <html>  <head>    <title>login.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript">function changeCode() {var img = document.getElementsByTagName("img")[0];img.src = "/161220/servlet/confirmCode”}</script>  </head>    <body>    <form action="#" method="post">    用户名:<input type="text" name="userName"/><br>    密码:<input type="password" name="pwd"/><br>    验证码:<input type="text" name="confirmCode"/>    <img src="/161220/servlet/confirmCode" onclick="changeCode()"/>    <a href="javascript:changeCode()">看不清换一张</a><br>    <input type="submit" value="登录"/><br>    </form>  </body></html>

原因是:更新src后,如果src与原来的相同,则浏览器回从缓存里获取图片而不会向后台发送新的请求。

解决办法:可以在src之后加上一些没有意义的随机参数比如链接上“?time=new Date().getTime()”即获取当前时间的时间戳,这是浏览器会认为这是不同的url因此会重新发送请求加载新的图片。

应用场景:比如在刷新验证码图片时。

修改后的代码:

<!DOCTYPE html> <html>  <head>    <title>login.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=UTF-8">        <!--<link rel="stylesheet" type="text/css" href="./styles.css">--><script type="text/javascript">function changeCode() {var img = document.getElementsByTagName("img")[0];img.src = "/161220/servlet/confirmCode?time=" + new Date().getTime();}</script>  </head>    <body>    <form action="#" method="post">    用户名:<input type="text" name="userName"/><br>    密码:<input type="password" name="pwd"/><br>    验证码:<input type="text" name="confirmCode"/>    <img src="/161220/servlet/confirmCode" onclick="changeCode()"/>    <a href="javascript:changeCode()">看不清换一张</a><br>    <input type="submit" value="登录"/><br>    </form>  </body></html>


0 0