您的位置:首页 > Web前端 > JQuery

怎样使用jquery刷新验证码图片

2017-03-08 18:38 316 查看
之所以普通的做法无法实现实时更新,是因为被浏览器缓存了,所以加了个时间戳

参考:http://blog.csdn.net/fengyu09/article/details/50393856

How
to refresh the src of <img /> with jQuery?

<img src="test.php" />


where test.PHP generates an image with a random number.

Itried :
$('#verifyimage').click(function() {
$(this).attr('src',$(this).attr('src'));
});


But it doesn't work.

Add a timestamp or a random number:
var timestamp = new Date().getTime();
$(this).attr('src',$(this).attr('src') + '?' +timestamp );


怎样使用jQuery刷新验证码图片?

(使用ajax读取django返回的 image/gif,不可行。)

在点击图片时,在其Src属性上增加一个随机数,使用时间戳即可。

附代码:

[java] view
plain copy

/** 

 * 验证码,提交前验证 

 */  

$(document).ready(function(){  

    var validated = false;  

    $.ajaxSetup({  

      dataType: "json",  

      beforeSend: function(xhr){  

          var csrftoken = $.cookie('csrftoken');  

          xhr.setRequestHeader("X-CSRFToken", csrftoken);  

      }  

    });  

    // 验证码输入失去焦点  

    $("#id_code").blur(function() {  

        //alert(1);  

        $.post(  

            $("#id_url_check").val(),  

            {"code": $("#id_code").val()},  

            function (data) {  

                if (data.status == true)  

                    validated = true;  

            }  

        );  

    });  

  

    // 提交表单  

    $("form").submit(function(event){  

        if (validated)  

           return true;  

        else {  

            $( "span" ).text( "验证码不正确。" ).show().fadeOut( 3000 );  

            // 更换验证码  

            var timestamp = new Date().getTime();  

            $("#id_img_captcha").attr("src", $("#id_url_captcha").val() + '?' +timestamp );  

            event.preventDefault();  

            }  

        }  

    );  

  

    // 点击更换验证码  

    $('#id_img_captcha').click(function() {  

        var timestamp = new Date().getTime();  

        $(this).attr("src", $("#id_url_captcha").val() + '?'+ timestamp);  

});  

//  

});  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: