CRUD
- Create:
- Method (POST):
- Respuesta 200 - OK
- Respuesta 204 - Sin contenido
- Respuesta 404 - No encontrado
- Respuesta 409 - Conflicto, ya existe
- Method (POST):
- Read:
- Method (GET):
- Respuesta 200 - OK
- Respuesta 404 - No encontrado
- Method (GET):
- Update:
- Method (PUT):
- Respuesta 200 - OK
- Respuesta 204 - Sin contenido
- Respuesta 404 - No encontrado
- Method (PUT):
- Delete:
- Method (DELETE):
- Respuesta 200 - OK
- Respuesta 404 - No encontrado
- Method (DELETE):
-
Por tipología:
- 1xx Informativas
- 2xx Peticiones Correctas
- 3xx Redirecciones
- 4xx Errores Cliente
- 5xx Errores Servidor
Con Jquery
function peticionJqueryAjax (url) {
$.ajax({
dataType: "json",
url: url,
})
.done(function( data, textStatus, jqXHR ) {
if ( console && console.log ) {
console.log( "La solicitud se ha completado correctamente." );
console.log( data );
}
})
.fail(function( jqXHR, textStatus, errorThrown ) {
if ( console && console.log ) {
console.log( "La solicitud a fallado: " + textStatus);
}
});
}
peticionJqueryAjax ("<---URL---->");
Vainilla JS
- readyState:
- 0 es uninitialized
- 1 es loading
- 2 es loaded
- 3 es interactive
- 4 es complete
function peticionAjax(url) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
console.info(JSON.parse(xmlHttp.responseText));
} else if (xmlHttp.readyState === 4 && xmlHttp.status === 404) {
console.error("ERROR! 404");
console.info(JSON.parse(xmlHttp.responseText));
}
};
xmlHttp.open("GET", url, true);
xmlHttp.send();
}
peticionAjax("<---URL---->");
-
JSON.parse()
- Analiza la cadena y retorna los valores
-
JSON.stringify()
- Analiza los valores y retorna una cadena
-
json (formato)
{ foo: 'bar' }
-
callback (cliente)
mycallback = function(data){ alert(data.foo); };
-
peticion (cliente)
var url = "http://www.example.net/sample.aspx?callback=mycallback";
-
respuesta (servidor)
mycallback({ foo: 'bar' });
-
Ejemplo de CORS y JSONP con php de formandome
<?php header('content-type: application/json; charset=utf-8'); header("access-control-allow-origin: *"); //Cadena de conexión: $connect = mysql_connect("localhost", "usuario", "pwd") or die('Could not connect: ' . mysql_error()); //seleccionamos bbdd: $bool = mysql_select_db("database", $connect); if ($bool === False){ print "No puedo encontrar la bbdd: $database"; } //inicializamos el cliente en utf-8: mysql_query('SET names utf8'); $query = "SELECT * FROM futbolistas"; $result = mysql_query($query) or die("SQL Error: " . mysql_error()); $data = array(); // obtenemos los datos: while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $data[] = array( 'id' => $row['id'], 'nombre' => $row['nombre'], 'apellido' => $row['apellido'], 'posicion' => $row['posicion'], 'equipo' => $row['equipo'], 'dorsal' => $row['dorsal'], 'desc' => $row['desc'], 'imagen' => $row['imagen'] ); } //codificamos en json: $json = json_encode($data); //enviamos json o jsonp según venga o no una función de callback: echo isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json; ?>
Soporte en cliente (librerías):
- Jquery:
// Using YQL and JSONP $.ajax({ url: "http://query.yahooapis.com/v1/public/yql", // The name of the callback parameter, as specified by the YQL service jsonp: "callback", // Tell jQuery we're expecting JSONP dataType: "jsonp", // Tell YQL what we want and that we want JSON data: { q: "select title,abstract,url from search.news where query=\"cat\"", format: "json" }, // Work with the response success: function( response ) { console.log( response ); // server response } });
- jsonp.js de Przemek Sobstel
- J50Npi.js de Roberto Decurnex
1 - Sacar en el html los datos de polen.
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
var datos = (JSON.parse(xmlHttp.responseText));
var contenido = "";
datos.forEach(function(estacion) {
contenido += "<h1>" + estacion.name + " (" + estacion.id + ")</h1>"
contenido += "<ul>"
for (var medicion in estacion.mediciones) {
contenido += "<li>" + medicion + ": <i>" + estacion.mediciones[medicion]["resumen"] + "</i></li>"
}
contenido += "</ul>"
})
document.body.innerHTML = contenido;
} else if (xmlHttp.readyState === 4 && xmlHttp.status === 404) {
console.error("ERROR! 404");
console.info(JSON.parse(xmlHttp.responseText));
}
};
xmlHttp.open("GET", "http://airemad.com/api/v1/pollen", true);
xmlHttp.send();
2 - Sacar en el html el tiempo meteorológico de Madrid, Barcelona y Valencia. Nota: http://openweathermap.org te será de gran ayuda, busca la solución al error 401
var contenido = "";
function temperaturaCiudad (ciudad) {
var xmlHttp = new XMLHttpRequest(),
APIKey = '', // Puedes usar una cuenta gratuita -> http://openweathermap.org/price
cURL = 'http://api.openweathermap.org/data/2.5/weather?q='+ciudad+'&APPID='+APIKey;
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
var datos = (JSON.parse(xmlHttp.responseText));
contenido += "<h1>"+datos.name+"</h1>"
contenido += "<p>"+datos.weather[0].description+"</p>"
document.body.innerHTML = contenido;
} else if (xmlHttp.readyState === 4 && xmlHttp.status === 404) {
datos = JSON.parse(xmlHttp.responseText);
console.error("ERROR! 404");
console.info(datos);
}
};
xmlHttp.open( "GET", cURL, true );
xmlHttp.send();
}
temperaturaCiudad("Madrid");
temperaturaCiudad("Barcelona");
temperaturaCiudad("Valencia");
3 - Jugando con datos abiertos, saquemos los detalles de todos los cuadros eléctricos de Gijón por consola.
function peticionAjax (url) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
var datos = (JSON.parse(xmlHttp.responseText));
console.log(datos)
} else if (xmlHttp.readyState === 4 && xmlHttp.status === 404) {
console.error("ERROR! 404");
console.info(JSON.parse(xmlHttp.responseText));
}
};
xmlHttp.open( "GET", url, true );
xmlHttp.send();
}
peticionAjax("http://opendata.gijon.es/descargar.php?id=163&tipo=JSON");
// Podemos encontrar errores en las respuestas.
// cuadromando[5] ...
calle: "Faustina Álvarez García"
latitud: 43.526376045
longitud: -5.685764873
numero: ""
potencia_w_: 17321
// ...