Open futianshen opened 5 years ago
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
PHP Prepare Statement
$data
json_encode
echo
fetch_assoc to json
[PHP] array_push 陣列中增加資料 [How do I properly use PHP to encode MySQL object into JSON?]()
解決方法:在 conn.php 加上 UTF8 編碼
$conn->query("SET NAMES 'UTF8'");
解決 PHP/mySQL 資料庫讀取中文顯示亂碼或問號
解決步驟:
urlencode
urldecode
如何在php中將陣列(array)轉成JSON格式---json_encode中文utf8
Week8 Homework3
js/main.js
php/products.php
如何使用 Fetch API 進行前後端串接?
參考資料
基礎 Fetch API
[1] 遇到問題:如何將資料庫的商品資料打包成陣列傳給前端?
解決步驟:
PHP Prepare Statement
取出資料$data
json_encode
編碼echo
將 陣列印出關鍵字
fetch_assoc to json
參考資料
[PHP] array_push 陣列中增加資料 [How do I properly use PHP to encode MySQL object into JSON?]()
[2] 遇到問題:中文資料變成 ???????
解決方法:在 conn.php 加上 UTF8 編碼
參考資料
解決 PHP/mySQL 資料庫讀取中文顯示亂碼或問號
[3] 遇到問題:中文資料遇到 json 編碼之後變成 \u7b2c\u4e00\u6... 亂碼
解決步驟:
urlencode
進行編碼json_encode
編碼urldecode
解碼參考資料
如何在php中將陣列(array)轉成JSON格式---json_encode中文utf8