【问题标题】:How to create Ajax refresh for django-simple-captcha如何为 django-simple-captcha 创建 Ajax 刷新
【发布时间】:2013-09-29 03:10:34
【问题描述】:

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

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

【问题讨论】:

    标签: django captcha


    【解决方案1】:

    选择的答案是使用 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 %}
    

    Forms.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>
    

    【讨论】:

      【解决方案2】:

      这是一个在 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;
          });
      });
      

      那么你只需要为captcha-refresh 类添加一些CSS,或者在&lt;a&gt; 中放置一张图片就可以了!

      【讨论】:

      • 我在我的 html 中添加了这个 &lt;a href="#void" class="captcha-refresh"&gt;&lt;i class="fa fa-refresh"&gt;&lt;/i&gt;&lt;/a&gt; 但验证码不刷新
      猜你喜欢
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 2014-01-12
      • 1970-01-01
      • 2011-06-18
      相关资源
      最近更新 更多