Lidemy / mentor-program-2nd-futianshen

mentor-program-2nd-futianshen created by GitHub Classroom
14 stars 2 forks source link

如何使用 Fetch API 進行前後端串接? #17

Open futianshen opened 5 years ago

futianshen commented 5 years ago

Week8 Homework3

js/main.js

$(document).ready(function(){
  let url = 'php/products.php'
  fetch(url, {method: 'POST'}).then(function(resp){
    resp.json().then(function(data){
   })
})

php/products.php

<?php
require_once('conn.php');
/* 怎樣將資料庫的商品資料打包成陣列? [1]*/
$stmt = $conn->prepare("SELECT id, name, quantity, price FROM products");
$stmt->execute();
$result = $stmt->get_result();
//$row=$result->fetch_assoc();
//echo ($row['name']);  [2] 中文資料變成 ??????????? 亂碼
//echo json_encode($row);  [3] 中文資料經過 json 編碼之後呈現亂碼
$data = array(); 
if ($result->num_rows) {
  while($row=$result->fetch_assoc()) {
    /* 將資料中的中文欄位取出編碼後,放回原來的欄位 */
    $row['name']=urlencode($row['name']);
    /* 將每一列資料放入陣列 */
    array_push($data, $row);
  }
}
/* 將陣列使用 json 編碼之後解碼回中文 */
$arr = urldecode(json_encode($data));
echo $arr;
?>

如何使用 Fetch API 進行前後端串接?

參考資料

基礎 Fetch API

[1] 遇到問題:如何將資料庫的商品資料打包成陣列傳給前端?

解決步驟:

  1. 使用 PHP Prepare Statement 取出資料
  2. 宣告一個形態為陣列的變數 $data
  3. 使用 if 和 迴圈將每一列物件資料存入陣列當中
  4. 經過 json_encode 編碼
  5. 使用 echo 將 陣列印出

    關鍵字

    fetch_assoc to json

參考資料

[PHP] array_push 陣列中增加資料 [How do I properly use PHP to encode MySQL object into JSON?]()

[2] 遇到問題:中文資料變成 ???????

解決方法:在 conn.php 加上 UTF8 編碼

$conn->query("SET NAMES 'UTF8'"); 

參考資料

解決 PHP/mySQL 資料庫讀取中文顯示亂碼或問號

[3] 遇到問題:中文資料遇到 json 編碼之後變成 \u7b2c\u4e00\u6... 亂碼

解決步驟:

  1. 將中文資料用 urlencode 進行編碼
  2. 將上一步編碼過後的資料替代原始資料
  3. 將資料經過 json_encode 編碼
  4. 將上一步編碼過後的資料使用 urldecode 解碼

參考資料

如何在php中將陣列(array)轉成JSON格式---json_encode中文utf8