Javascript 使用jQuery-ajax的不可见ReCaptcha
我正在尝试使用jQuery和“ajax”请求在表单中实现最新的ReCaptcha(也称为“不可见的”ReCaptcha)。Javascript 使用jQuery-ajax的不可见ReCaptcha,javascript,jquery,ajax,recaptcha,invisible-recaptcha,Javascript,Jquery,Ajax,Recaptcha,Invisible Recaptcha,我正在尝试使用jQuery和“ajax”请求在表单中实现最新的ReCaptcha(也称为“不可见的”ReCaptcha)。 ReCaptcha文件: 我的表格: <form id="myForm" > <input type="email" name="email" /><br /> <input type="password" name="password" /><br/> <!--<input t
ReCaptcha文件: 我的表格:
<form id="myForm" >
<input type="email" name="email" /><br />
<input type="password" name="password" /><br/>
<!--<input type="submit" value="log in" />-->
<button class="g-recaptcha" data-sitekey="6LdK..." data-callback="onSubmit">log in</button>
</form>
<div id="status"></div>
登录
我的javascript(jQuery):
提交函数(令牌){
document.getElementById(“myForm”).submit();
}
$(文档).ready(函数(){
$(“#myForm”).submit(函数(事件){
event.preventDefault();
var data=$(“#myForm”).serialize();
$.ajax({
类型:“POST”,
url:“test.php”,
数据:数据,
数据类型:“json”,
beforeSend:function(){
$(“#status”).html(“登录…”);
},
成功:功能(响应){
$(“#status”).html(response.text);
if(response.type==“success”){
window.location.replace(“/myaccount”);
}
},
错误:函数(){
$(“#status”).html(“失败”);
}
});
});
});
ReCaptcha需要设置一个“数据回调”,我不确定如何与我已经存在的.submit(函数(事件)”函数绑定。我的“onSubmit()”技巧无效,它会忽略“ajax”并刷新页面。
如何在“datas”变量中发送“g-recaptcha-response”值以将其发布到test.php?
<script defer>
function onSubmit(token) {
var f = $("#myForm");
$.ajax({
type: "POST",
url: "test.php",
data: f.serialize(),
dataType: "json",
beforeSend: function(){
$("#status").html("logging in...");
},
success: function(response){
$("#status").html(response.text);
if(response.type=="success"){
window.location.replace("/myaccount");
} else {
$("#status").html("Captcha failed.");
}
},
error: function(){
$("#status").html("Failed.");
}
});
}
</script>
函数onSubmit(令牌){
var f=$(“#myForm”);
$.ajax({
类型:“POST”,
url:“test.php”,
数据:f.serialize(),
数据类型:“json”,
beforeSend:function(){
$(“#status”).html(“登录…”);
},
成功:功能(响应){
$(“#status”).html(response.text);
if(response.type==“success”){
window.location.replace(“/myaccount”);
}否则{
$(“#status”).html(“验证码失败”);
}
},
错误:函数(){
$(“#status”).html(“失败”);
}
});
}
在test.php中,您需要在服务器端验证验证码:
<?php
if(isset($_POST['g-recaptcha-response'])) {
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=[YOUR_SECRET_KEY]&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
if($result['success'] == 1) {
// Captcha ok
} else {
// Captcha failed
}
}
?>
下面是我在深入挖掘了InvisibleRecaptcha的文档后如何解决这个问题的,显然我对JS(很酷的东西)不太熟悉,所以我学习了一点jQuery:
我的头上用javascript标记(还有一点css来移除丑陋的谷歌徽章):
window.onScriptLoad=函数(){
//这个回调在加载后将由recaptcah/api.js调用
//render=explicit作为脚本src中的param,那么我们可以在此时显式地呈现reCaptcha
//元素“呈现”中不可见的验证码
var htmlEl=document.querySelector('.g-recaptcha');
//验证码选项
变量captchaOptions={
sitekey:'您的站点密钥…',
大小:'不可见',
//对实际函数的引用
回调:window.onUserified
};
//仅适用于“不可见”类型。如果为true,则将从html元素的data-*属性中读取值(如果该属性未通过CAPTCHOPTIONS传递)
var inheritFromDataAttr=true;
//现在渲染
recaptchaId=window.grecaptcha.render(htmlEl、captchaOptions、inheritFromDataAttr);
};
window.onUserified=函数(令牌){
您的ajax代码。。。。
}
$(“博客查询”)。点击(功能(e){
//var gg=grecaptcha.getresponse();
var token=window.grecaptcha.getResponse(recaptchaId);
//如果没有令牌,则表示尚未验证用户
如果(!令牌){
window.grecaptcha.execute(recaptchaId);
返回;
}
});
`
@13h15我有完全相同的问题,你找到解决方案了吗?@VinZ是的,尽快发布你的提交
需要处理/添加令牌
到$.ajax
调用,类似于批准的解决方案。批准的解决方案是在我的解决方案之后添加的。仅供参考,你通过移除徽章来破坏google TOS。把它放在某处就行了n使用data badge=inline和CSW回答旧问题时,如果您包含一些上下文来解释您的答案如何有帮助,尤其是对于已经有公认答案的问题,您的答案对其他StackOverflow用户会更有用。请参阅:。
<?php
if(isset($_POST['g-recaptcha-response'])) {
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=[YOUR_SECRET_KEY]&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
if($result['success'] == 1) {
// Captcha ok
} else {
// Captcha failed
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=fr" async defer></script>
<style>
.grecaptcha-badge{
display:none;
}
</style>
<script>
var onloadCallback = function(){
grecaptcha.render("emplacementRecaptcha",{
"sitekey": "YOUR_RECAPTCHA_SITEKEY_HERE",
"badge": "inline",
"type": "image",
"size": "invisible",
"callback": onSubmit
});
};
var onSubmit = function(token){
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var userTfaOtp = $("#userTfaOtp").val();
$.ajax({
type: "POST",
url: location.href,
data:{
userEmail: userEmail,
userPassword: userPassword,
userTfaOtp: userTfaOtp,
userJetonRecaptcha: token
},
dataType: "json",
beforeSend: function(){
$("#statutConnexion").html("Traitement de votre requête d'authentification en cours...");
},
success: function(response){
$("#statutConnexion").html(response.Message);
if(response.Victoire){
$("#formulaireConnexion").slideUp();
window.location.replace("/compte");
}
else{
grecaptcha.reset();
}
},
error: function(){
$("#statutConnexion").html("La communication avec le système d'authentification n'a pas pu être établie. Veuillez réessayer.");
grecaptcha.reset();
}
});
};
function validate(event){
event.preventDefault();
$("#statutConnexion").html("Validation de votre épreuve CAPTCHA en cours...");
grecaptcha.execute();
}
function onload(){
var element = document.getElementById("boutonConnexion");
element.onclick = validate;
}
</script>
<div id="formulaireConnexion">
<input type="email" name="userEmail" id="userEmail" placeholder="Courriel" title="Courriel" required="required" /><br />
<input type="password" name="userPassword" id="userPassword" placeholder="Mot de passe" title="Mot de passe" required="required" /><br/>
<input type="text" name="userTfaOtp" id="userTfaOtp" placeholder="Double authentification (optionnelle)" autocomplete="off" pattern="[0-9]{6}" title="Six caractères numériques" maxlength="6" /><br />
<div id="emplacementRecaptcha"></div>
<button id="boutonConnexion">Connexion</button>
</div>
<div id="statutConnexion"></div>
<script>onload();</script>
$jsonVictoire = true; // boolean
$jsonMessage = 'anything you want to tell your visitor'; // string
$return =
json_encode(
array(
'Victoire'=>$jsonVictoire,
'Message'=>$jsonMessage
)
);
die($return);
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<div id="login_page" class="g-recaptcha" data-size="invisible" data-sitekey="your sitekey" data-callback="login_page"></div>
<script>
window.onScriptLoad = function () {
// this callback will be called by recaptcah/api.js once its loaded. If we used
// render=explicit as param in script src, then we can explicitly render reCaptcha at this point
// element to "render" invisible captcha in
var htmlEl = document.querySelector('.g-recaptcha');
// option to captcha
var captchaOptions = {
sitekey: 'your site key...',
size: 'invisible',
// reference to an actual function
callback: window.onUserVerified
};
// Only for "invisible" type. if true, will read value from html-element's data-* attribute if its not passed via captchaOptions
var inheritFromDataAttr = true;
// now render
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token){
Your ajax code....
}
$("#blog_inquiry").click(function(e){
//var gg = grecaptcha.getresponse();
var token = window.grecaptcha.getResponse(recaptchaId);
// if no token, mean user is not validated yet
if (!token) {
window.grecaptcha.execute(recaptchaId);
return;
}
});
</script>`