我在一个页面上有两个 ajax 表单,它们都是部分 View 。两者都有 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'
});
表单中的验证码如下所示:
<div id="recaptcha1"></div>
我正在使用 MVC 5,我对表单提交的 Controller 操作是这样的:
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);
}
我尝试了多种组合,其中不同的东西被加载到不同的地方,但我找不到一个没有错误的组合。当任一表单已提交且验证失败时,我可以在各自的表单上同时获得两个 recaptcha 的最佳方法是什么?
最佳答案
我在通过 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>
关于javascript - 同一页面上的多个 Recaptcha 在提交失败时消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36837393/