Bas*_*asj 12 javascript forms ajax captcha recaptcha
使用"我不是机器人"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>
Run Code Online (Sandbox Code Playgroud)
然后一些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) { }
}); } });
Run Code Online (Sandbox Code Playgroud)
如何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>
Run Code Online (Sandbox Code Playgroud)
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);
});
}
});
Run Code Online (Sandbox Code Playgroud)
关键是使用回调(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>
Run Code Online (Sandbox Code Playgroud)
然后使用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 );
});
});
Run Code Online (Sandbox Code Playgroud)
正如您将注意到我已经使用.done而.fail不是success和error,这是处理响应的首选方式.
| 归档时间: |
|
| 查看次数: |
10171 次 |
| 最近记录: |