Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

XmlHttpRequest GET data is empty

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...