如何解决XmlHttpRequest GET 数据为空
我尽量避免使用 jQuery 和完美的 $.ajax 函数,但我遇到了一些问题:我的 PHP API 没有收到参数。
// 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));
}
}
还有我的 PHP 文件:
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);
我最后的警报返回:
{"email":null,"password":null,"date":"16:28"}
我看到了类似的问题,但答案不起作用:
- 添加
header('Access-Control-Allow-Headers: Content-Type,Authorization');
- 使用
$json = file_get_contents('php://input'); $obj = json_decode($json); $obj['email'];
有什么想法吗?非常感谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。