La forma más sencilla de realizar peticiones AJAX recibiendo los datos en forma de objetos JSON es utilizar el método getJSON() (el cual emplea el método GET para realizarlas). Veamos un ejemplo.
index1.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>InformaticaPC | JSON con JQuery I</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
</style>
<script type="text/javascript" src="../lib/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Dar el foco al recuadro del código
$("#codigo").focus();
// -----------------------------
// Al hacer clic en el botón para buscar
$("#calcular").click(function()
{
// Enviar la petición mediante GET
$.getJSON("json1.php",
{ _num1 : $("#num1").val(), _num2 : $("#num2").val() },
mostrarDatos);
});
});
// -----------------------------
// Carga los datos recibidos en los cuadros de texto
function mostrarDatos( datos )
{
$("#resultado").attr("value", datos.resultado );
}
</script>
</head>
<body>
<label for="num1">Número 1:</label>
<input type="text" name="num1" id="num1" size="2" value="25" readonly="readonly" />
<label for="num2">Número 2:</label>
<input type="text" name="num2" id="num2" size="2" value="4" readonly="readonly" />
<label for="resultado">Resultado:</label>
<input type="text" name="resultado" id="resultado" value="" readonly="readonly" />
<input type="button" name="calcular" id="calcular" value="Calcular" />
</body>
</html>
json1.php:
<?php
if( !empty($_GET) && isset($_GET['_num1']) && isset($_GET['_num2']) )
{
$resultado = $_GET['_num1'] * $_GET['_num2'];
// Devolver el resultado en formato JSON
echo '{ "resultado" : '.$resultado.' }';
}
else
{
echo "Acceso no autorizado";
}
?>
Otra forma más completa de usar JSON es con el método ajax() (explicado anteriormente) definiendo su propiedad dataType con valor 'json'.
Veamos a continuación un ejemplo (observa cómo se construye en PHP la cadena en formato JSON antes de devolverla).
index2.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>InformaticaPC | JSON con JQuery II</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
#codigo { text-align:center; }
#log { color:yellow;background-color:red;margin-bottom:10px; }
</style>
<script type="text/javascript" src="../lib/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Dar el foco al recuadro del código
$("#codigo").focus();
// -----------------------------
// Al hacer clic en el botón para buscar
$("#buscar").click(function()
{
var codigo = $("#codigo").val();
$("#log").text( "Código a buscar: [" + codigo + "]" );
// Enviar la petición mediante POST
$.ajax({
async: true,
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "json2.php",
data: "codigo="+codigo,
beforeSend: antesEnvio,
success: mostrarDatos,
timeout: 4000,
error: errorEnvio
});
return false;
});
});
// -----------------------------
// Antes de enviar los datos
function antesEnvio() {
$("#log").text("Se procesa la función 'antesEnvio()' antes de enviarse los datos...");
}
// -----------------------------
// En caso de error
function errorEnvio() {
$("#log").text("Ha ocurrido un error!");
}
// -----------------------------
// Carga los datos recibidos en los cuadros de texto
function mostrarDatos( datos )
{
$("#nombre").attr("value", datos.nombre );
$("#apellidos").attr("value", datos.apellido1 + " " + datos.apellido2 );
$("#fnac").attr("value", datos.fnac );
$("#cuota").attr("value", datos.cuota );
}
</script>
</head>
<body>
<div id="log"> </div>
<p>Introduce un código del 1 al 3:</p>
<label for="codigo">Código:</label>
<input type="text" name="codigo" id="codigo" size="2" maxlength="2" value="" />
<input type="button" name="buscar" id="buscar" value="Buscar" /><p />
<label for="nombre">Nombre:</label>
<input type="text" name="nombre" id="nombre" value="" readonly="readonly" /><br />
<label for="apellidos">Apellidos:</label>
<input type="text" name="apellidos" id="apellidos" value="" readonly="readonly" /><br />
<label for="fnac">F/Nacimiento:</label>
<input type="text" name="fnac" id="fnac" value="" readonly="readonly" size="10" /><br />
<label for="cuota">Cuota:</label>
<input type="text" name="cuota" id="cuota" value="" readonly="readonly" size="4" />
</body>
</html>
json2.php:
<?php
if( !empty($_POST) && isset($_POST['codigo']) )
{
switch( $_POST['codigo'] )
{
case 1:
echo '{ "nombre":"Pedro", "apellido1":"Manrique", "apellido2":"Sosa", "fnac":"15/02/1970", "cuota":20 }';
break;
case 2:
echo '{ "nombre":"Raquel", "apellido1":"Vera", "apellido2":"Déniz", "fnac":"15/07/1972", "cuota":22 }';
break;
case 3:
echo '{ "nombre":"Antonio", "apellido1":"Ronda", "apellido2":"Cuadrado", "fnac":"20/11/1974", "cuota":30 }';
break;
default:
echo "Código no encontrado";
}
}
else
{
echo "Acceso no autorizado";
}
?>
En el ejemplo anterior hemos enviamos un único valor a PHP, pero dado que estamos tratando con JSON es posible enviar un objeto que contenga otros datos:
index3.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>InformaticaPC | JSON con JQuery III</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
#log { color:yellow;background-color:red;margin-bottom:10px; }
</style>
<script type="text/javascript" src="../lib/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Dar el foco al recuadro del código
$("#codigo").focus();
// -----------------------------
// Al hacer clic en el botón para calcular
$("#calcular").click(function()
{
var operacion = $("#operacion").val();
var num1 = $("#num1").val();
var num2 = $("#num2").val();
// Creamos un objeto con los datos a enviar
var objDatos = { "_operacion" : operacion, "_num1" : num1, "_num2" : num2 };
// Enviar la petición mediante POST
$.ajax({
async: true,
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "json3.php",
data: objDatos,
success: mostrarDatos,
beforeSend: antesEnvio,
timeout: 4000,
error: errorEnvio
});
return false;
});
});
// -----------------------------
// Antes de enviar los datos
function antesEnvio() {
$("#log").text("Se procesa la función 'antesEnvio()' antes de enviarse los datos...");
}
// -----------------------------
// En caso de error
function errorEnvio() {
$("#log").text("Ha ocurrido un error!");
}
// -----------------------------
// Mostrar el resultado
function mostrarDatos( datos )
{
$("#resultado").attr("value", datos.resultado);
}
</script>
</head>
<body>
<div id="log"> </div>
<label for="operacion">Operación:</label>
<input type="text" name="operacion" id="operacion" size="2" value="SUMA" readonly="readonly" />
<label for="num1">Número 1:</label>
<input type="text" name="num1" id="num1" size="2" value="30" readonly="readonly" />
<label for="num2">Número 2:</label>
<input type="text" name="num2" id="num2" size="2" value="50" readonly="readonly" />
<label for="resultado">Resultado:</label>
<input type="text" name="resultado" id="resultado" value="" readonly="readonly" />
<input type="button" name="calcular" id="calcular" value="Calcular" />
</body>
</html>
json3.php:
<?php
if( !empty($_POST) && isset($_POST['_operacion']) )
{
$resultado = $_POST['_num1'] + $_POST['_num2'];
if( $_POST['_operacion'] == "SUMA")
echo '{ "resultado" : '.$resultado.' }';
else
echo '{ "resultado" : -1 }';
}
else
{
echo "Acceso no autorizado";
}
?>
Para finalizar veamos un último ejemplo en el que desde PHP se devuelve un array de objetos JSON (observa que en esta ocasión usamos la función de PHP json_encode() para convertir un array a formato JSON en lugar de devolver directamente la cadena que lo representa).
index4.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>InformaticaPC | JSON con JQuery IV</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
#log { color:yellow;background-color:red;margin-bottom:10px; }
#resultado { background-color:lightgray;margin-top:10px; }
</style>
<script type="text/javascript" src="../lib/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
// Dar el foco al recuadro del código
$("#codigo").focus();
// -----------------------------
// Al hacer clic en el botón para buscar
$("#cargar").click(function()
{
// Enviar la petición mediante POST
$.ajax({
async: true,
type: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "json4.php",
beforeSend: antesEnvio,
success: mostrarDatos,
timeout: 4000,
error: errorEnvio
});
return false;
});
});
// -----------------------------
// Antes de enviar los datos
function antesEnvio() {
$("#log").text("Se procesa la función 'antesEnvio()' antes de enviarse los datos...");
}
// -----------------------------
// En caso de error
function errorEnvio() {
$("#log").text("Ha ocurrido un error!");
}
// -----------------------------
// Carga los datos recibidos en los cuadros de texto
function mostrarDatos( aDatos )
{
var html;
html = "<p>Se encontraron [" + aDatos.length + "] registro(s)</p>";
html += "<table border='1'>";
html += "<thead>";
html += "<tr>";
html += "<th>Nombre</th>";
html += "<th>Apellido 1º</th>";
html += "<th>Apellido 2º</th>";
html += "<th>F/Nacimiento</th>";
html += "<th>Cuota</th>";
html += "</tr>";
html += "</thead>";
for( var contador=0; contador < aDatos.length; contador++ )
{
html += "<tr>";
html += "<td>" + aDatos[contador].nombre + "</td>";
html += "<td>" + aDatos[contador].apellido1 + "</td>";
html += "<td>" + aDatos[contador].apellido2 + "</td>";
html += "<td>" + aDatos[contador].fnac + "</td>";
html += "<td>" + aDatos[contador].cuota + "</td>";
html += "</tr>";
}
html += "</table>";
$("#resultado").html( html );
}
</script>
</head>
<body>
<div id="log"> </div>
<input type="button" name="cargar" id="cargar" value="Cargar datos" />
<div id="resultado"> </div>
</body>
</html>
json4.php:
<?php
$aDatos = array();
$aDatos[] = array( 'nombre' => 'Pedro', 'apellido1' => 'Manrique', 'apellido2' => 'Sosa', 'fnac' => '15/02/1970', 'cuota' => 20 );
$aDatos[] = array( 'nombre' => 'Raquel', 'apellido1' => 'Vera', 'apellido2' => 'Déniz', 'fnac' => '15/07/1972', 'cuota' => 22 );
$aDatos[] = array( 'nombre' => 'Antonio', 'apellido1' => 'Ronda', 'apellido2' => 'Cuadrado', 'fnac' => '20/11/1974', 'cuota' => 30 );
// Utilizamos la función de PHP 'json_encode()' para convertir el array a formato JSON antes de devolverlo
echo json_encode($aDatos);
?>

Vea también: [ AJAX ] - [ getJSON() ] - [ ajax() ] - [ json_encode() ] - [ json_decode() ]