如何在保留 reCaptcha 脚本的同时使用 jQuery/AJAX 加载 reCaptcha 表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7261436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I load a reCaptcha form using jQuery/AJAX while leaving the reCaptcha scripts in place?
提问by eSentrik
I load my contact form into my page with JQuery/AJAX.
我使用 JQuery/AJAX 将我的联系表单加载到我的页面中。
The contact form contains the reCaptcha scripts.
联系表单包含 reCaptcha 脚本。
Unfortunately, JQuery removes the script tags before inserting them into my page. These script tags are needed because they output the captcha. now my loaded form has no captcha.
不幸的是,JQuery 在将脚本标签插入我的页面之前删除了它们。需要这些脚本标签,因为它们输出验证码。现在我加载的表单没有验证码。
采纳答案by benck
The link has all you need: http://code.google.com/apis/recaptcha/docs/display.html
该链接包含您需要的一切:http: //code.google.com/apis/recaptcha/docs/display.html
You can't add the script in ajax. You should add the following line before :
你不能在ajax中添加脚本。您应该在之前添加以下行:
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
Then, you can dynamically create a recaptcha form in your js code by using adding the following code:
然后,您可以通过添加以下代码在您的 js 代码中动态创建一个 recaptcha 表单:
Recaptcha.create("your_public_key",
"element_id",
{
theme: "red",
callback: Recaptcha.focus_response_field
}
);
回答by Oleg
@benck, great answer! But it's become a bit outdated. The current script URL is:
@benck,很好的答案!但它变得有点过时了。当前的脚本 URL 是:
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js"></script>
And the code should be like below:
代码应该如下所示:
grecaptcha.render('element_id', {
sitekey: recaptchaSiteKey,
callback: function(response) {
console.log(response);
}
});
回答by szmegma
My approach is a bit different:
我的方法有点不同:
<script src='https://www.google.com/recaptcha/api.js?render=explicit' async defer></script>
<form>
<input name="whatEver" type="text">
<div id="captcha"></div>
<button>submit</button>
</form>
<script>
var captchaWidgetId = grecaptcha.render( 'captcha', {
'sitekey' : 'your_site_key'
'theme' : 'light'
});
$(document).ready(function(){
$('form').on('click','button', function(e){
var formDatas = $(this).closest('form').serialize()+'&response='+grecaptcha.getResponse(captcha);
$.post('post.php', formDatas, function(data){
//successful
});
});
});
</script>