PHP代码
<?php
header('Content-type: application/json; charset=utf-8');
$servername = "localhost:3306";
$username=$_GET['name'];
$password=$_GET['password'];
$database=$_GET['database'];
//连接数据库
try {
$conn = new PDO("mysql:host=$servername;dbname=$database;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Query the database for parking lot names and available spots
$sql = "SELECT P_name, P_all_count - P_reserve_count - P_reserve_count AS surplus FROM parking;";
$result = $conn->query($sql);
// Create an empty array to store the parking lot information
$parking_lots = [];
// Loop through the query result and populate the array with parking lot names and available spots
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$parking_lot = [
"place_names" => $row["P_name"],
"place_number" => $row["surplus"]
];
array_push($parking_lots, $parking_lot);
}
// Convert the array to a JSON object and encode it
$json_output = json_encode($parking_lots);
$json_output = urlencode($json_output);
// Send the JSON object to the frontend
echo $json_output;
} catch(PDOException $e) {
echo "连接失败:".$e->getMessage();
}
?>
小程序端代码
wx.request({
url: 'http://ip:66/connect_get.php',
data: {
name: '',
password: '',
database: '',
},
header: {
'content-type': 'application/json;'
},
success: (res) => {
var place = JSON.parse(decodeURIComponent(res.data));
console.log(place);
console.log("读取数据成功");
},
fail: (f) => {
wx.showModal({
title: '提示',
content: '读取数据失败',
});
}
})
encodeURIComponent() 函数对返回的 JSON 字符串进行编码,然后在小程序中使用 decodeURIComponent() 函数进行解码。
乱码举例
[{“place_names”:“\u65b0\u5de5\u505c\u8f66\u573a”,“place_number”:“300”},{“place_names”:“\u6cb3\u5e08\u5927\u505c\u8f66\u573a”,“place_number”:“356”},{“place_names”:“\u80d6\u4e1c\u6765\u505c\u8f66\u573a”,“place_number”:“70”},{“place_names”:“\u9f99\u4ead\u505c\u8f66\u573a”,“place_number”:“44”},{“place_names”:“\u536b\u8f89\u505c\u8f66\u573a”,“place_number”:“200”},{“place_names”:“\u539f\u9633\u505c\u8f66\u573a”,“place_number”:“286”},{“place_names”:“\u7ea2\u65d7\u505c\u8f66\u573a”,“place_number”:“440”}]