Documente Academic
Documente Profesional
Documente Cultură
La forma ms sencilla de realizar peticiones AJAX recibiendo los datos en forma de objetos JSON es utilizar
el mtodo getJSON() (el cual emplea el mtodo GET para realizarlas). Veamos un ejemplo.
index1.html:
<head>
5.
6.
7.
8.
9.
10.
<style type="text/css">
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
</style>
11.
12.
13.
14.
<script type="text/javascript">
15.
16.
$(document).ready(function()
17.
18.
19.
20.
$("#codigo").focus();
21.
22.
// -----------------------------
23.
24.
25.
$("#calcular").click(function()
26.
27.
28.
$.getJSON("json1.php",
29.
30.
mostrarDatos);
31.
});
32.
33.
});
34.
35.
// -----------------------------
36.
37.
38.
39.
40.
41.
$("#resultado").attr("value", datos.resultado );
}
42.
43.
44.
</script>
</head>
45.
46.
<body>
47.
48.
49.
50.
51.
52.
53.
54.
<label for="resultado">Resultado:</label>
55.
56.
57.
58.
59.
</body>
60.
61. </html>
Collapse Code
json1.php:
1. <?php
2.
3.
4.
{
$resultado = $_GET['_num1'] * $_GET['_num2'];
5.
6.
7.
8.
9.
else
10.
11.
12.
13. ?>
Collapse Code
Otra forma ms completa de usar JSON es con el mtodo ajax() (explicado anteriormente) definiendo su
propiedad dataType con valor 'json'.
Veamos a continuacin un ejemplo (observa cmo se construye en PHP la cadena en formato JSON antes de
devolverla).
index2.html:
<head>
5.
6.
7.
8.
<style type="text/css">
9.
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
10.
#codigo { text-align:center; }
11.
#log { color:yellow;background-color:red;margin-bottom:10px; }
12.
</style>
13.
14.
15.
16.
<script type="text/javascript">
17.
18.
$(document).ready(function()
19.
20.
21.
22.
$("#codigo").focus();
23.
24.
// -----------------------------
25.
26.
27.
$("#buscar").click(function()
28.
29.
30.
31.
32.
33.
$.ajax({
34.
async: true,
35.
type: "POST",
36.
dataType: "json",
37.
38.
url: "json2.php",
39.
data: "codigo="+codigo,
40.
beforeSend: antesEnvio,
41.
success: mostrarDatos,
42.
timeout: 4000,
43.
error: errorEnvio
44.
});
45.
46.
return false;
47.
});
48.
49.
});
50.
51.
// -----------------------------
52.
53.
54.
function antesEnvio() {
55.
56.
57.
58.
// -----------------------------
59.
60.
61.
// En caso de error
function errorEnvio() {
62.
63.
64.
65.
// -----------------------------
66.
67.
68.
69.
70.
$("#nombre").attr("value", datos.nombre );
71.
72.
$("#fnac").attr("value", datos.fnac );
73.
$("#cuota").attr("value", datos.cuota );
74.
75.
76.
77.
</script>
</head>
78.
79.
<body>
80.
81.
82.
83.
84.
85.
<label for="codigo">Cdigo:</label>
86.
87.
88.
89.
90.
<label for="nombre">Nombre:</label>
91.
readonly="readonly" /><br /
>
92.
93.
<label for="apellidos">Apellidos:</label>
94.
95.
96.
<label for="fnac">F/Nacimiento:</label>
97.
98.
99.
<label for="cuota">Cuota:</label>
100.
="4" />
101.
102.
</body>
103.
104.
</html>
Collapse Code
json2.php:
1. <?php
2.
3.
4.
5.
switch( $_POST['codigo'] )
6.
7.
case 1:
8.
9.
break;
10.
case 2:
11.
12.
break;
13.
case 3:
14.
15.
break;
16.
default:
17.
18.
19.
20.
else
21.
22.
23.
24.
25. ?>
Collapse Code
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:
<head>
5.
6.
7.
8.
<style type="text/css">
9.
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
10.
#log { color:yellow;background-color:red;margin-bottom:10px; }
11.
</style>
12.
13.
14.
15.
<script type="text/javascript">
16.
17.
$(document).ready(function()
18.
19.
20.
21.
$("#codigo").focus();
22.
23.
// -----------------------------
24.
25.
26.
$("#calcular").click(function()
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
$.ajax({
37.
async: true,
38.
type: "POST",
39.
dataType: "json",
40.
41.
url: "json3.php",
42.
data: objDatos,
43.
success: mostrarDatos,
44.
beforeSend: antesEnvio,
45.
timeout: 4000,
46.
error: errorEnvio
47.
});
48.
49.
return false;
50.
});
51.
52.
});
53.
54.
// -----------------------------
55.
56.
57.
function antesEnvio() {
58.
59.
60.
61.
// -----------------------------
62.
63.
// En caso de error
64.
function errorEnvio() {
65.
66.
67.
68.
// -----------------------------
69.
70.
71.
// Mostrar el resultado
72.
73.
$("#resultado").attr("value", datos.resultado);
74.
75.
76.
77.
</script>
</head>
78.
79.
<body>
80.
81.
82.
83.
<label for="operacion">Operacin:</label>
84.
85.
86.
87.
88.
89.
90.
91.
92.
<label for="resultado">Resultado:</label>
93.
94.
95.
96.
97.
</body>
98.
99. </html>
Collapse Code
json3.php:
1. <?php
2.
3.
4.
5.
6.
7.
8.
else
9.
10.
11.
else
12.
13.
14.
15. ?>
Collapse Code
Para finalizar veamos un ltimo ejemplo en el que desde PHP se devuelve un array de objetos JSON (observa
que en esta ocasin usamos la funcin de PHP json_encode() para convertir un array a formato JSON en
lugar de devolver directamente la cadena que lo representa).
index4.php:
<head>
5.
6.
7.
8.
<style type="text/css">
9.
body { background-color:lightyellow;font-family:Arial;font-size:10pt; }
10.
#log { color:yellow;background-color:red;margin-bottom:10px; }
11.
#resultado { background-color:lightgray;margin-top:10px; }
12.
</style>
13.
14.
15.
16.
<script type="text/javascript">
17.
18.
$(document).ready(function()
19.
20.
21.
22.
$("#codigo").focus();
23.
24.
// -----------------------------
25.
26.
27.
$("#cargar").click(function()
28.
29.
30.
$.ajax({
31.
async: true,
32.
type: "POST",
33.
dataType: "json",
34.
35.
url: "json4.php",
36.
beforeSend: antesEnvio,
37.
success: mostrarDatos,
38.
timeout: 4000,
39.
error: errorEnvio
40.
});
41.
42.
43.
return false;
});
44.
45.
});
46.
47.
// -----------------------------
48.
49.
50.
function antesEnvio() {
51.
52.
53.
54.
// -----------------------------
55.
56.
57.
// En caso de error
function errorEnvio() {
58.
59.
60.
61.
// -----------------------------
62.
63.
64.
65.
66.
{
var html;
67.
68.
69.
70.
71.
html +=
72.
html +=
73.
html +=
"<th>Nombre</th>";
74.
html +=
"<th>Apellido 1</th>";
75.
html +=
"<th>Apellido 2</th>";
76.
html +=
"<th>F/Nacimiento</th>";
77.
html +=
"<th>Cuota</th>";
78.
html +=
79.
html +=
"<thead>";
"<tr>";
"</tr>";
"</thead>";
80.
81.
82.
83.
html += "<tr>";
84.
85.
86.
87.
88.
+ "</td>";
89.
+ "</td>";
90.
91.
92.
93.
html += "</tr>";
}
+ "</td>";
94.
html += "</table>";
95.
96.
$("#resultado").html( html );
97.
98.
99.
</script>
100.
</head>
101.
102.
<body>
103.
104.
105.
106.
107.
108.
109.
110.
</body>
111.
112.
</html>
Collapse Code
json4.php:
1. <?php
2.
$aDatos = array();
3.
4.
$aDatos[] = array( 'nombre' => 'Pedro', 'apellido1' => 'Manrique', 'apellido2' =>
'Sosa', 'fnac' => '15/02/1970', 'cuota' => 20 );
5.
$aDatos[] = array( 'nombre' => 'Raquel', 'apellido1' => 'Vera', 'apellido2' => 'D
niz', 'fnac' => '15/07/1972', 'cuota' => 22 );
6.
$aDatos[] = array( 'nombre' => 'Antonio', 'apellido1' => 'Ronda', 'apellido2' => '
Cuadrado', 'fnac' => '20/11/1974', 'cuota' => 30 );
7.
8.
9.
echo json_encode($aDatos);
10. ?>
Collapse Code