I try to avoid jQuery and the perfect $.ajax function, but I'm encountering some problems: my PHP API doesn't receive params.
// Appel de l'API
// Identification
var authentification_email = document.getElementById('authentification_email').value;
var authentification_password = document.getElementById('authentification_password').value;
var params = '?email=' + authentification_email + '&password=' + authentification_password;
let xhr = new XMLHttpRequest();
xhr.open('GET', urlApi, true);
xhr.responseType = "json";
xhr.setRequestHeader('Content-Type', 'application/json/x-www-form-urlencoded; charset=UTF-8');
xhr.send(params);
xhr.onload = function() {
if (xhr.status != 200) {
alert("Erreur " + xhr.status + " : " + xhr.statusText);
} else {
alert(JSON.stringify(xhr.response));
}
}
And my PHP file :
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Content-Type: application/json;charset=utf-8');
$return = array(
'email' => $_GET['email'],
'password' => $_GET['password'],
'date' => date('H:i')
);
echo json_encode($return);
And my final alert return :
{"email":null,"password":null,"date":"16:28"}
I saw similar questions, but the answers didn't work :
- Add
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With, Authorization');
- Use
$json = file_get_contents('php://input'); $obj = json_decode($json); $obj['email'];
Any ideas? Thanks a lot!
question from:
https://stackoverflow.com/questions/65904335/xmlhttprequest-get-data-is-empty 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…