如何使用ajax / jquery访问类?

时间:2015-05-05 14:26:52

标签: jquery ajax

我在文件夹ImageCaptcha

中有一个班级
 private string GetCaptchaText(int length)
    {
        var possibleCaptchaCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        var result = "";
        Random random = new Random();
        for (int index = 0; index < length; index++)
        {
            result += possibleCaptchaCharacters[(int)Math.Ceiling(random.NextDouble() * possibleCaptchaCharacters.Length - 1)].ToString();

        }
        return result;
    }

我还在注册页面上显示了具有属性的图像

<button id="refresh"><img src="~/Images/captcha-refresh.png" height="22" width="29" alt="" onclick="reFreshCaptchaImage()"></button>

我可以从函数GetCaptchaText获取数据,该函数返回随机数..带有ajax,因为我在下面使用这个脚本时总是会出错吗?

 function reFreshCaptchaImage() {

        $.ajax({
            type: 'GET',
            url: "../CaptchaImage/test/Index",
            success: function (msg) {

                alert(msg);
            },
            error: function () {
                alert("error");
            }
        });
    }

我想在不刷新整页的情况下刷新该部分

1 个答案:

答案 0 :(得分:0)

您无法直接从AJAX调用C#类。你需要在这两者之间安装某种处理程序。

例如,您可以设置ashx文件来返回图像,在该文件中,您可以调用C#类。

以下是使用泛型处理程序(ashx文件)的教程:
http://www.dotnetperls.com/ashx

这是一个通过通用处理程序创建验证码的教程:
http://www.codeproject.com/Articles/99148/Simple-CAPTCHA-Create-your-own-in-C

当你有一个可以返回图像的处理程序时,你可以简单地刷新图像。我在这里找到了另一个问题,讨论了这个问题:
Refresh image with a new one at the same url