9

我正在为我的基于 django 的网站使用 django-simple-captcha 应用程序,我能够将验证码表单字段集成到我的表单中,但问题是,如何创建一个调用 Ajax 刷新的按钮来刷新验证码图像点击?该应用程序的文档不是很清楚,我尝试按照文档中给出的示例进行操作,但它不起作用。请帮我解决这个问题?

编辑:这是 django 包的链接: django-simple-captcha

4

2 回答 2

21

这是javascript中的一个有效实现:

$(function() {
    // Add refresh button after field (this can be done in the template as well)
    $('img.captcha').after(
            $('<a href="#void" class="captcha-refresh">Refresh</a>')
            );

    // Click-handler for the refresh-link
    $('.captcha-refresh').click(function(){
        var $form = $(this).parents('form');
        var url = location.protocol + "//" + window.location.hostname + ":"
                  + location.port + "/captcha/refresh/";

        // Make the AJAX-call
        $.getJSON(url, {}, function(json) {
            $form.find('input[name="captcha_0"]').val(json.key);
            $form.find('img.captcha').attr('src', json.image_url);
        });

        return false;
    });
});

然后你只需要为这个类添加一些 CSS captcha-refresh,或者在里面放一张图片<a>就可以了!

于 2013-12-04T09:41:06.427 回答
0

选择的答案是使用 jQuery 而不是 JavaScript。

如果使用纯 JavaScript,你应该这样做。这也将刷新音频,而不仅仅是 django-simple-captcha 使用的图像。

https://django-simple-captcha.readthedocs.io/en/latest/advanced.html#rendering

FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'

custom_field.html:

    ​
{% load i18n %}
{% spaceless %}

  <label class="control-label">{{ label }}</label>
        <img src="{{ image }}" alt="captcha" class="captcha" />
<br/>
<audio id="audio" controls>
  <source id="audioSource" src="{{ audio }}" />
</audio>
      {% include "django/forms/widgets/multiwidget.html" %}
{% endspaceless %}

表格.py:

    ​
    class CustomCaptchaTextInput(CaptchaTextInput):
        template_name = 'custom_field.html'
    ​
    class Form(forms.Form):
        captcha = CaptchaField(widget=CustomCaptchaTextInput)
    ​
        def __init__(self, *args, **kwargs):
            super(Form, self).__init__(*args, **kwargs)
            self.fields['captcha'].widget.attrs['placeholder'] = 'Solve the captcha'
            self.fields['captcha'].label = "Captcha"

在 body 标签的末尾添加:

<script>
const captchas = document.querySelectorAll('img.captcha')

function headers(options) {
  options = options || {}
  options.headers = options.headers || {}
  options.headers['X-Requested-With'] = 'XMLHttpRequest'
  return options
}

for (const captcha of captchas) {
  const anchor = document.createElement('a')
  anchor.href = '#void'
  anchor.classList.add('captcha-refresh')
  anchor.textContent = 'Refresh'
  anchor.addEventListener('click', ({ target }) => {
    const url = `${window.location.origin}/captcha/refresh/`
    let formEl = target.parentElement

    while (formEl && formEl.tagName.toLowerCase() !== 'form') {
      formEl = formEl.parentElement
    }

    fetch(url, headers())
      .then(res => res.json())
      .then(json => {
        formEl.querySelector('input[name="captcha_0"]').value = json.key
        captcha.setAttribute('src', json.image_url)
        document.getElementById('audioSource').setAttribute('src', json.audio_url)
        document.getElementById('audio').load()
      })
      .catch(console.error)

    return false
  })

  captcha.after(anchor)
}
</script>
于 2020-06-16T04:12:32.840 回答