使用jquery刷新Captcha图像

Refresh Captcha image with jquery

本文关键字:图像 Captcha 刷新 jquery 使用      更新时间:2023-09-26

我在剃刀页面上有一个HTML图像标签。此图显示生成的captcha。我添加了一些jquery,以便在单击此图像时刷新它。这在我的电脑上有效,但一旦我将其发布到服务器,点击图像时就不会发生任何事情。

<img id="captcha-image" src="@Url.Action("Captcha", "Home")" />
...
$("#captcha-image").click(function () {
    this.src = "@Url.Action("Captcha", "Home")";
});

编辑:
我已经确定发生这种情况是因为浏览器可能缓存了图像。现在我想在GET请求中发送一个随机数,这样浏览器缓存就不会否定我的努力。

现在的问题是如何在适当的地方获得随机数:

$("#captcha-image").click(function () {
    this.src = "@Url.Action("Captcha", "Home", new { r = System.Random.Next() })";
});

这将不起作用,因为Next()System.Random中不是一个静态方法,并且我需要一个Random对象来引用才能使用它

我还尝试使用JavaScript随机方法:

$("#captcha-image").click(function () {
    var randomNumber = Math.floor(Math.random());
    this.src = "@Url.Action("Captcha", "Home", new { r = randomNumber})";
});

这里的问题是变量randomNumber@Url.Action中的c#代码块的作用域中不可见。

您可以使用replace更改带有其值的randomNumber字符串,也可以将外部双引号更改为单引号,并将randomNumber传递给匿名对象初始值设定项。

this.src = '@Url.Action("Captcha", "Home", new { randomNumber = "_randomNumber_"})'.replace("_randomNumber_", randomNumber );

另一种方法可以是将服务器端代码与javascript连接起来,使查询字符串

this.src = '@Url.Action("Captcha", "Home")?randomNumber' + randomNumber ;
//Put This one Partial view
<img src="@Url.Action("GetCaptchaImage", "Vulpith_Public",new { dt=@DateTime.Now},Request.Url.Scheme)" />


     //And call ajax from this partial view as following
function Captcharefresh() {
$.ajax({
             url: "../Vulpith_Public/_GetCaptcha",
             type: "post",
             dataType: "html",
             data: {},
success: function (data) {
    $('#codeRefresh').html(data)
},
error: function (data) {
}
});
}

//and create actions as following
public FileResult GetCaptchaImage(DateTime dt)
{
    CaptchaRandomImage CI = new CaptchaRandomImage();
    this.Session["CaptchaImageText"] = CI.GetRandomString(5); // here 5 means I want to get 5 char long captcha
    //CI.GenerateImage(this.Session["CaptchaImageText"].ToString(), 300, 75);
    // Or We can use another one for get custom color Captcha Image 
    CI.GenerateImage(this.Session["CaptchaImageText"].ToString(), 300, 75, Color.DarkGray, Color.White);
    MemoryStream stream = new MemoryStream();
    CI.Image.Save(stream, ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(stream, "image/png");
}

//One more action as
[HttpPost]
public ActionResult _GetCaptcha()
{
    return PartialView();
}