[英]Using PHP cURL to POST JSON data
我正在為學校開發一個三層登錄系統,並且無法使用 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 格式,所以你需要添加這個 header:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.