微信小程序在调用php API时中文乱码问题解决

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”}]

解决乱码后也可直接赋值

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值