Un uso común de JSON es leer datos de un servidor web, y mostrar los datos en una página web.
Este capítulo le enseñará cómo intercambiar datos JSON entre el cliente y un servidor PHP.
PHP tiene algunas funciones integradas para manejar JSON.
Los objetos en PHP se pueden convertir a JSON usando la función PHP json_encode():
<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New
York";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
Aquí hay un JavaScript en el cliente, usando una llamada AJAX para solicitar PHP archivo del ejemplo anterior:
Utilice JSON.parse() para convertir el resultado en un objeto 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();
Pruébelo usted mismo →
<!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>
Los arreglos en PHP también se convertirán a JSON cuando se use la función PHP json_encode():
<?php
$myArr = array("John", "Mary", "Peter", "Sally");
$myJSON = json_encode($myArr);
echo $myJSON;
?>
Aquí hay un JavaScript en el cliente, usando una llamada AJAX para solicitar PHP archivo del ejemplo de matriz anterior:
Utilice JSON.parse() para convertir el resultado en una matriz de 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();
Pruébelo usted mismo →
<!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 es un lenguaje de programación del lado del servidor y se puede utilizar para acceder a una base de datos.
Imagine que tiene una base de datos en su servidor y desea enviar una solicitud a desde el cliente donde solicita las 10 primeras filas en una tabla llamada "clientes".
En el cliente, cree un objeto JSON que describa el número de filas que desea devolver.
Antes de enviar la solicitud al servidor, convierta el objeto JSON en un string y enviarlo como parámetro a la url de la página PHP:
Utilice JSON.stringify() para convertir el objeto JavaScript en 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();
Pruébelo usted mismo →
<!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>
Defina un objeto que contenga una propiedad y un valor de "límite".
Convierta el objeto en una cadena JSON.
Envíe una solicitud al archivo PHP, con la cadena JSON como parámetro.
Espere hasta que la solicitud regrese con el resultado (como JSON)
Muestra el resultado recibido del archivo PHP.
Eche un vistazo al archivo 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);
?>
Convierta la solicitud en un objeto, usando la función PHP json_decode().
Acceda a la base de datos y complete una matriz con los datos solicitados.
Agregue la matriz a un objeto y devuelva el objeto como JSON usando la función 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;
}
Pruébelo usted mismo →
<!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>
Al enviar datos al servidor, suele ser mejor utilizar el método HTTP POST
.
Para enviar solicitudes AJAX utilizando el método POST
, especifique el método y el encabezado correcto.
Los datos enviados al servidor ahora deben ser un argumento para el método 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);
Pruébelo usted mismo →
<!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>
La única diferencia en el archivo PHP es el método para obtener los datos transferidos.
Utilice $_POST en lugar de $_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);
?>