การใช้งานทั่วไปของ JSON คือการอ่านข้อมูลจากเว็บเซิร์ฟเวอร์ และแสดงข้อมูลบนหน้าเว็บ
บทนี้จะสอนวิธีแลกเปลี่ยนข้อมูล JSON ระหว่างกัน ไคลเอนต์และเซิร์ฟเวอร์ PHP
PHP มีฟังก์ชันในตัวเพื่อจัดการ JSON
ออบเจ็กต์ใน PHP สามารถแปลงเป็น JSON ได้โดยใช้ฟังก์ชัน PHP json_encode():
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New
York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
นี่คือ JavaScript บนไคลเอนต์ โดยใช้การเรียก AJAX เพื่อขอ PHP ไฟล์จากตัวอย่างด้านบน:
ใช้ JSON.parse() เพื่อแปลงผลลัพธ์เป็นวัตถุ JavaScript:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
xmlhttp.open("GET", "demo_file.php");
xmlhttp.send();
</script>
</body>
</html>
อาร์เรย์ใน PHP จะถูกแปลงเป็น JSON เมื่อใช้ฟังก์ชัน PHP json_encode():
<?php
$myArr = array("John", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);
echo $myJSON;
?>
นี่คือ JavaScript บนไคลเอนต์ โดยใช้การเรียก AJAX เพื่อขอ PHP ไฟล์จากตัวอย่างอาร์เรย์ด้านบน:
ใช้ JSON.parse() เพื่อแปลงผลลัพธ์เป็นอาร์เรย์ JavaScript:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>Get JSON Data from a PHP Server</h2>
<p>Convert the data into a JavaScript array:</p>
<p id="demo"></p>
<script>
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj[2];
}
xmlhttp.open("GET", "demo_file_array.php");
xmlhttp.send();
</script>
</body>
</html>
PHP เป็นภาษาโปรแกรมฝั่งเซิร์ฟเวอร์ และสามารถใช้เพื่อเข้าถึงฐานข้อมูลได้
ลองนึกภาพคุณมีฐานข้อมูลบนเซิร์ฟเวอร์ของคุณและคุณต้องการส่งคำขอไปที่ จากไคลเอนต์ที่คุณขอ 10 แถวแรกในตารางที่เรียกว่า "ลูกค้า"
บนไคลเอ็นต์ ให้สร้างออบเจ็กต์ JSON ที่อธิบายจำนวนแถวที่คุณต้องการส่งคืน
ก่อนที่คุณจะส่งคำขอไปยังเซิร์ฟเวอร์ ให้แปลงออบเจ็กต์ JSON เป็น สตริงและส่งเป็นพารามิเตอร์ไปยัง URL ของหน้า PHP:
ใช้ JSON.stringify() เพื่อแปลงวัตถุ JavaScript เป็น JSON:
const limit = {"limit":10};
const dbParam = JSON.stringify(limit);
xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET","json_demo_db.php?x=" + dbParam);
xmlhttp.send();
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>Get JSON Data from a PHP Server</h2>
<p>The JSON received from the PHP file:</p>
<p id="demo"></p>
<script>
const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>
</body>
</html>
กำหนดวัตถุที่มีคุณสมบัติและค่า "จำกัด "
แปลงวัตถุให้เป็นสตริง JSON
ส่งคำขอไปยังไฟล์ PHP โดยมีสตริง JSON เป็นพารามิเตอร์
รอจนกระทั่งคำขอส่งคืนพร้อมผลลัพธ์ (เป็น JSON)
แสดงผลที่ได้รับจากไฟล์ PHP
ดูไฟล์ PHP:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj =
json_decode($_GET["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$stmt = $conn->prepare("SELECT name FROM customers LIMIT ?");
$stmt->bind_param("s", $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
แปลงคำขอให้เป็นวัตถุโดยใช้ฟังก์ชัน PHP json_decode().
เข้าถึงฐานข้อมูลและกรอกอาร์เรย์ด้วยข้อมูลที่ร้องขอ
เพิ่มอาร์เรย์ให้กับออบเจ็กต์ และส่งคืนออบเจ็กต์เป็น JSON โดยใช้ ฟังก์ชัน json_encode()
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
let text = "";
for (let x in myObj) {
text += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>Get JSON Data from a PHP Server</h2>
<p id="demo"></p>
<script>
const obj = { "limit":10 };
const dbParam = JSON.stringify(obj);
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
myObj = JSON.parse(this.responseText);
let text = ""
for (let x in myObj) {
text += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = text;
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam);
xmlhttp.send();
</script>
<p>Try changing the "limit" property from 10 to 5.</p>
</body>
</html>
เมื่อส่งข้อมูลไปยังเซิร์ฟเวอร์ วิธีที่ดีที่สุดคือใช้เมธอด HTTP POST
หากต้องการส่งคำขอ AJAX โดยใช้วิธี POST
ให้ระบุวิธีการและส่วนหัวที่ถูกต้อง
ข้อมูลที่ส่งไปยังเซิร์ฟเวอร์ตอนนี้จะต้องเป็นอาร์กิวเมนต์ของเมธอด send()
:
const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const myObj = JSON.parse(this.responseText);
let text ="";
for (let x in myObj) {
text += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
ลองด้วยตัวคุณเอง →
<!DOCTYPE html>
<html>
<body>
<h2>Use HTTP POST to Get JSON Data from a PHP Server</h2>
<p id="demo"></p>
<script>
const dbParam = JSON.stringify({"limit":10});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
myObj = JSON.parse(this.responseText);
let text = "";
for (let x in myObj) {
text += myObj[x].name + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
xmlhttp.open("POST", "json_demo_db_post.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>
<p>Try changing the "limit" property from 10 to 5.</p>
</body>
</html>
ข้อแตกต่างเพียงอย่างเดียวในไฟล์ PHP คือวิธีการรับข้อมูลที่ถ่ายโอน
ใช้ $_POST แทน $_GET:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj =
json_decode($_POST["x"], false);
$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$stmt = $conn->prepare("SELECT name FROM customers LIMIT ?");
$stmt->bind_param("s",
$obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>