使用"I am not a robot" Recpatcha的传统方法似乎是在客户端使用<form>
:
<form action="post.php" method="POST">
<div class="g-recaptcha" data-sitekey="6Lc_0f4SAAAAAF9ZA_d7Dxi9qRbPMMNW-tLSvhe6"></div>
<button type="submit">Sign in</button>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
然后一些g-recaptcha-response
将被发送到服务器。
然而,在我的代码中,我不使用<form>
,而是一个AJAX调用:
$('#btn-post').click(function(e) {
$.ajax({
type: "POST",
url: "post.php",
data: {
action: 'post',
text: $("#text").val(),
ajaxMode: "true"
},
success: function(data) { },
error: function(data) { }
}); } });
用这个溶液如何得到g-recaptcha-response
的答案?
我只是分别不使用任何表单和提交机制来实现它。因此,这是一个纯AJAX解决方案。
HTML代码:<div id="recaptcha-service" class="g-recaptcha"
data-callback="recaptchaCallback"
data-sitekey=""></div>
<script type="text/javascript" src="https://www.google.com/recaptcha/api.js?hl=en"></script>
JavaScript代码:
window.recaptchaCallback = undefined;
jQuery(document).ready(function($) {
window.recaptchaCallback = function recaptchaCallback(response) {
$.ajax({
method: "POST",
url: "http://example.com/service.ajax.php",
data: { 'g-recaptcha-response': response },
})
.done(function(msg) {
console.log(msg);
})
.fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
}
});
关键是使用回调(在本例中为recaptchaCallback
)。
您可以在https://gist.github.com/martinburger/f9f37770c655c25d5f7b179278815084上找到更完整的示例。该示例在服务器端使用了Google的PHP实现(https://github.com/google/recaptcha)。
使用表单时,中断表单的提交。按常规设置表单:
<form action="post.php" method="POST" id="my-form">
<div class="g-recaptcha" data-sitekey="6Lc_0f4SAAAAAF9ZA_d7Dxi9qRbPMMNW-tLSvhe6"></div>
<input type="text" id="text">
<button type="submit">Sign in</button>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
然后使用jQuery中断表单的提交并序列化它,允许您通过Ajax传递数据:
$('#my-form').submit(function(e) {
e.preventDefault();
$this = $(this);
$.ajax({
type: "POST",
url: "post.php",
data: $this.serialize()
}).done(function(data) {
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
正如您将注意到的,我使用了.done
和.fail
而不是success
和error
,这是处理响应的首选方式。
为了答案的完整性,假设您只想使用一个链接,您可以…
<form id="g-recap">
<div class="g-recaptcha" data-sitekey="{{ gcaptcha key }}" ></div>
</form>
<a href="/recaptchaured/path">Verify</a>
$('a').on('click',function(e) {
e.preventDefault();
document.location = $(this).attr('href') + '?' + $('#g-recap').serialize()
});