我正在使用 reCaptcha v2 但在开发控制台响应中 Uncaught (in promise) null
在任何情况下(并移动 .reset()
功能)
安慰:
我的recaptcha代码:
<div class="text-xs-center" style="text-align: center; height:150px;">
<p style="color: black;"> Complete the verification: </p>
<div style="display: inline-block;" class="g-recaptcha" data-sitekey="xxxxxxxxxxx" data-callback="callback"></div>
</div>
我的回调函数:
function callback() {
if (grecaptcha === undefined) {
alert('Recaptcha non definito');
return;
}
var response = grecaptcha.getResponse();
console.log(response);
if (!response) {
alert('Coud not get recaptcha response');
return;
}
$.ajax({
'url' : 'validate-recaptcha.php',
'type' : 'POST',
'data' : {
'response' : response
},
'success' : function(data) {
alert('Data: '+data);
},
'error' : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
grecaptcha.reset();
}
和我的 validate-recaptcha.php :
<?php
//debug
$fp = fopen('debug.txt', 'a');
fwrite($fp, print_r($_POST, TRUE));
fclose($fp);
//enddebug
if (empty($_POST['recaptcha'])) {
exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
array (
'response' => $response,
'secret' => 'yoursecretkey',
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$opts = array('http' =>
array (
'method' => 'POST',
'header' => 'application/x-www-form-urlencoded',
'content' => $post
)
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');
在网上搜索,问题可能是 .reset()
功能,但我不明白解决方案。
原文由 FABBRj 发布,翻译遵循 CC BY-SA 4.0 许可协议
我也有这个错误,我发现与recaptcha回调有关(在你的情况下
data-callback="callback"
)。如果您删除数据回调属性,则不会出现错误。控制台错误
Uncaught (in promise) null
表明回调正在等待一个承诺。这是使用 Promise 的 recaptcha 的基本回调函数:在您的情况下,您需要将代码调整为如下所示:
这是我在 SO 中的第一个答案,所以请耐心等待,如果我忘记或错过了什么,请告诉我:)