我正在为学校使用三层登录系统,在使用JSON + POST发送和接收消息时遇到问题。我有一个接受用户名和密码的前端:
<div id = "login form" style="text-align: center">
<input type="text" id="username" name ="username"><br>
<input type="password" id="password" name ="password"><br>
<button id="login"> Login</button>
<div>
然后使用AJAX将其发布到“前端的背面”-一个PHP脚本。前端的PHP脚本只是将同一条消息传递到中间,然后将其传递到后端,后端将查询数据库并返回结果。我为前端制作了以下PHP脚本:
header('Content-type: application/json');
$middle_url = "https://myurl.edu/";
$username = $_POST['username']; //extract credentials
$password = $_POST['password'];
// load new array
$credentials = array(
'username' => $username,
'password' => $password
);
$ch = curl_init(); // curl handle
curl_setopt($ch, CURLOPT_URL, $middle_url . "test.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials); // load credentials to POST
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // set return type to string
$middle_reply = curl_exec($curl); // execute curl and store response
curl_close($ch);
echo $middle_reply;
我的问题是,当我运行HTML文件时,结果得到一个空字符串,我不确定为什么。
我创建了一个测试文件,在该文件中,我像这样对返回值进行了硬编码:
<?php
header('Content-type: application/json');
$response = array(
'role' => 0
);
echo (json_encode($response));
?>
如果我将HTML直接连接到该测试文件,则会得到期望的数组,但是当我尝试首先通过前端PHP文件进行路由时,总是返回一个空字符串。请有人帮助我。
编辑:如果有帮助,这就是我从HTML文件中发布数据的方式:
<script>
const form = {
username: document.getElementById('username'),
password: document.getElementById('password'),
login: document.getElementById('login'),
};
form.login.addEventListener('click',validate);
function validate() {
var ajax = new XMLHttpRequest();
ajax.onload = function() {
if (this.status == 200) {
console.log(this.responseText);
const response = JSON.parse(this.responseText);
if(response['role'] == 1){
location.href = 'teacher.html';
}
else if (response['role'] == 0) {
location.href = 'student.html';
}
}
};
const postData = `username=${form.username.value} password=${form.password.value}`;
ajax.open('POST','login.php',true);
console.log(postData);
ajax.send(postData);
}
</script>
您需要在ajax请求中指定要发送的数据格式。
似乎您已经接近表单的urlencoded格式,因此您需要添加此标头:
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.send(postData);
并且您的参数必须用与号&
隔开,而不用空格:
const postData = `username=${form.username.value}&password=${form.password.value}`;
另外,您可能想用encodeURIComponent()转义数据,因为此刻,如果您的登录名或密码包含&符,它将破坏POST数据格式:
const username = `${form.username.value}` ;
const password = `${form.password.value}`
const postData = 'username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password);