【问题标题】:Multiple Recaptcha on same page disappearing on failed submit?同一页面上的多个 Recaptcha 在提交失败时消失?
【发布时间】:2016-04-25 10:00:16
【问题描述】:

我在一个页面上有两个 ajax 表单,它们都是部分视图。两者都有recaptcha,我似乎无法在表单提交且验证失败后找到recaptcha 重新加载的方法。

Recaptcha 是显式加载的,我有两个问题,首先如果我使用:

<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>

在这两种表单上,我都会收到“未捕获的错误 recaptcha 占位符元素必须为空”。所以我不能那样做。如果我将上面的内容与整个页面的整体布局一起加载,我会遇到第二个问题,即一旦表单提交不正确,recpatcha 将不会重新加载。

加载每个recaptcha的脚本如下:

var recaptcha1;
var recaptcha2;
var myCallBack = function () {

    //Render the recaptcha1 on the element with ID "recaptcha1"
    recaptcha1 = grecaptcha.render('recaptcha1', {
        'sitekey': 'sitekeyhere', 
        'theme': 'light'
    });


    //Render the recaptcha2 on the element with ID "recaptcha2"
    recaptcha2 = grecaptcha.render('recaptcha2', {
        'sitekey': 'sitekeyhere', 
        'theme': 'light'
    });

表格中的recaptcha如下所示:

<div id="recaptcha1"></div>

我使用的是 MVC 5,我的表单提交的控制器操作是这样的:

public async System.Threading.Tasks.Task<ActionResult> FormSubmit(contactform model, string whichpage)
    {if (ModelState.IsValid && status)

        {*Updates database/sends email here*

else
        {

            return PartialView("_contactform", model);

        }

我尝试了多种组合,将不同的东西加载到不同的位置,但我找不到一个没有错误的组合。当任一表单已提交且验证失败时,我可以在各自的表单上同时使用两种验证码的最佳方式是什么?

【问题讨论】:

    标签: javascript jquery ajax asp.net-mvc forms


    【解决方案1】:

    我在通过 ajax 提交表单时遇到了类似的问题。问题是当表单返回并调用回调函数时,它希望在两种表单中都呈现两个 ReCaptchas。由于一个 ReCaptcha 已经渲染,另一个 ReCaptcha 中断。要仅以正确的形式呈现 ReCaptcha,请添加以下 if 语句以检查 ReCaptcha 是否已在相关容器中呈现。该示例使用 jQuery。

    var myCallBack = function () {
      if($('#recaptcha1').is(':empty')) {
        grecaptcha.render('recaptcha1', {
          'sitekey': 'sitekeyhere', 
          'theme': 'light'
        });
      }
    
      if($('#recaptcha2').is(':empty')) {
        grecaptcha.render('recaptcha2', {
          'sitekey': 'sitekeyhere', 
          'theme': 'light'
        });
       }
    }
    

    您还需要确保两个 ReCaptcha 占位符元素都采用受尊重的形式。

    <form name="form1">
      [...]
      <div id="recaptcha1"></div>
    </form>
    
    <form name="form2">
      [...]
      <div id="recaptcha2"></div>
    </form>
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多