XmlHttpRequest使用POST方法将空白数据发送到php

时间:2018-08-20 10:43:10

标签: javascript php xmlhttprequest

我已经附加了两个文件,我正在尝试从服务器端验证recaptcha,并尝试使用XMLHttpRequest将grecaptcha.repsonse()传递给php,但是它使用POST发送空白数据。我能够获得相同的解决方案

以下代码具有XMLHttpRequest

<script type="text/javascript">
    function sendAjaxRequest() {
        if (grecaptcha === undefined) {
            alert('Recaptcha not defined'); 
            return; 
        }

        var response = grecaptcha.getResponse();

        if (!response) {
            alert('Coud not get recaptcha response'); 
            return; 
        }

        var http = new XMLHttpRequest();
        var url = 'validate-recaptcha.php';

        //Send the proper header information along with the request
        http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        temp = JSON.stringify(response);
        http.onreadystatechange = function() {
            if(http.readyState == 4 && http.status == 200) {
                alert(http.responseText);
            }
        }
        http.open('POST', url, true);
        http.send(response);
     }
</script>

以下是php代码:

<?php
if (empty($_POST['response'])) {
    exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(array (
    'response' => $response,
    'secret' => 'mysecretkey',
    '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');
?>  

0 个答案:

没有答案