Tutorial de JSONP
En este capítulo presentaremos el conocimiento sobre JSONP.
JSONP (JSON with Padding) es un "patrón de uso" de JSON que permite a las páginas web obtener datos de otros dominios (sitios web), es decir, leer datos entre dominios.
¿Por qué necesitamos una tecnología especial (JSONP) para acceder a datos desde diferentes dominios (sitios web)? Esto se debe a la política de mismo origen.
La política de mismo origen es una conocida política de seguridad propuesta por Netscape; hoy en día todos los navegadores que admiten JavaScript utilizan esta política.
Aplicación JSONP
1. Datos del servidor en formato JSONP
Por ejemplo, si el cliente desea acceder a:https://www.example.com/try/ajax/jsonp.php?jsoncallback=callbackFunction。
Supongamos que el cliente espera que se devuelvan los datos: ["customername1","customername2"].
Los datos que realmente se devuelven al cliente se muestran como: callbackFunction(["customername1","customername2"]).
El código del archivo del servidor jsonp.php es:
Código del archivo jsonp.php
<?php
header('Content-type: application/json');
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
$json_data = '["customername1","customername2"]';
echo $jsoncallback . "(" . $json_data . ")";
?>
2. El cliente implementa la función callbackFunction
<script type="text/javascript">
function callbackFunction(result, methodName)
{
var html = '<ul>';
for(var i = 0; i < result.length; i++)
{
html += '<li>' + result[i] + '</li>';
}
html += '</ul>';
document.getElementById('divCustomers').innerHTML = html;
}
</script>
Visualización de la página
<div id="divCustomers"></div>
Código completo de la página del cliente
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ejemplo de JSONP</title>
</head>
<body>
<div id="divCustomers"></div>
<script type="text/javascript">
function callbackFunction(result, methodName)
{
var html = '<ul>';
for(var i = 0; i < result.length; i++)
{
html += '<li>' + result[i] + '</li>';
}
html += '</ul>';
document.getElementById('divCustomers').innerHTML = html;
}
</script>
<script type="text/javascript" src="https://www.example.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script>
</body>
</html>
Uso de JSONP con jQuery
El código anterior puede utilizar el ejemplo de código jQuery:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ejemplo de JSONP</title>
<script src="https://cdn.static.example.com/libs/jquery/1.8.3/jquery.js"></script>
</head>
<body>
<div id="divCustomers"></div>
<script>
$.getJSON("https://www.example.com/try/ajax/jsonp.php?jsoncallback=?", function(data) {
var html = '<ul>';
for(var i = 0; i < data.length; i++)
{
html += '<li>' + data[i] + '</li>';
}
html += '</ul>';
$('#divCustomers').html(html);
});
</script>
</body>
</html>
Otras extensiones