PHP JSON
- Pagina precedente Server JSON
- Pagina successiva HTML JSON
JSON 的常规用途是从 web 服务器读取数据,然后在网页中显示这些数据。
本章向您讲解如何在客户端与 PHP 服务器之间交换 JSON 数据。
File PHP
PHP 提供处理 JSON 的内建函数。
通过使用 PHP 函数 json_encode()
,PHP 中的对象可转换为 JSON:
File PHP
<?php $myObj->name = "Bill Gates"; $myObj->age = 62; $myObj->city = "Seattle"; $myJSON = json_encode($myObj); echo $myJSON; ?>
JavaScript client-side
Questo è il JavaScript client-side sul client, che utilizza chiamate AJAX per richiedere il file PHP dell'esempio precedente:
Esempio
usare JSON.parse()
Converti i risultati in un oggetto JavaScript:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; }); }); xmlhttp.open("GET", "demo_file.php", true); xmlhttp.send();
Array PHP
Quando si utilizza la funzione PHP json_encode()
In questo caso, l'array in PHP verrà anche convertito in JSON:
File PHP
<?php $myArr = array("Bill Gates", "Steve Jobs", "Elon Musk"); $myJSON = json_encode($myArr); echo $myJSON; ?>
JavaScript client-side
Questo è il JavaScript client-side sul client, che utilizza chiamate AJAX per richiedere il file PHP dell'esempio precedente:
Esempio
Usa JSON.parse()
Converti i risultati in un array JavaScript:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj[2]; }); }); xmlhttp.open("GET", "demo_file_array.php", true); xmlhttp.send();
Database PHP
PHP è un linguaggio di programmazione server-side, che dovrebbe essere utilizzato per operazioni che possono essere eseguite solo dal server, come l'accesso al database.
Immagina di avere un database sul server che contiene dati di clienti, prodotti e fornitori.
Al momento, devi richiedere al server per ottenere i primi dieci record della tabella "clienti":
Esempio
Usa JSON.stringify()
Converti l'oggetto JavaScript in JSON:
obj = { "table":"customers", "limit":10 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; }); }); xmlhttp.open("GET", "demo_json_db.php?x=" + dbParam, true); xmlhttp.send();
Esempio di spiegazione:
- Definisci l'oggetto che contiene le proprietà 'table' e 'limit'.
- Converti questo oggetto in una stringa JSON.
- Inviare una richiesta a questo file PHP, con JSON come parametro.
- Attendere fino a che la richiesta restituisce i risultati (come JSON).
- Mostra i risultati ricevuti dal file PHP.
Visualizza il file PHP
File PHP
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_GET["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>
Spiegazione del file PHP:
- Converti la richiesta in oggetto utilizzando la funzione PHP
json_decode()
. - Accedi al database, riempi l'array con i dati richiesti.
- Aggiungi l'array all'oggetto utilizzando
json_encode()
La funzione restituisce l'oggetto come JSON.
Esegui una scansione dei risultati
Converti i risultati ricevuti dal file PHP in oggetto JavaScript, o nell'esempio di questo caso, un array JavaScript:
Esempio
usare JSON.parse()
Converti JSON in oggetto JavaScript:
... xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].name + "<br>"; }); document.getElementById("demo").innerHTML = txt; }); }); ...
Metodo PHP = POST
Quando si inviano dati al server, è meglio utilizzare il metodo HTTP POST.
Per inviare una richiesta AJAX utilizzando il metodo POST, specificare questo metodo e l'intestazione corretta.
I dati inviati al server devono essere ora .send();
Parametri del metodo:
Esempio
obj = { "table":"customers", "limit":10 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myObj = JSON.parse(this.responseText); for (x in myObj) { txt += myObj[x].name + "<br>"; }); document.getElementById("demo").innerHTML = txt; }); }); xmlhttp.open("POST", "demo_json_db.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("x=" + dbParam);
L'unica differenza tra il file PHP è il metodo di recupero dei dati trasmessi.
File PHP
usare $_POST
piuttosto che $_GET
:
<?php header("Content-Type: application/json; charset=UTF-8"); $obj = json_decode($_POST["x"], false); $conn = new mysqli("myServer", "myUser", "myPassword", "Northwind"); $result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit); $outp = array(); $outp = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($outp); ?>
- Pagina precedente Server JSON
- Pagina successiva HTML JSON