02 enero 2017

Incluir contenido de un archivo JSON con Ajax de JQuery

  7 comentarios

Ahora que esta de moda las API Rest en todo el medio de la Internet, es necesario innovar, y es que en eso pasamos nuestra vida los programadores, innovando e innovando, y como no ser así, si nuestra carrera en eso consiste. Las API Rest si no han escuchado antes el termino son un método de programacion que despeja por completo la relacion que hay entre un servidor y el cliente, llamese navegador.

Aunque este es un tema mas profundo y del cual hablare mas completo en una entrada futura, hoy solo quiero mencionar y enseñarles como mostrar datos de un Archivo JSON en una pagina común, mediante el uso de Ajax de jQuery para la funcionalidad asincrona que requiere este estilo de programacion.

A continuación, vamos a crear esta simple estructura para empezar nuestro proyecto.

<!DOCTYPE html>
<html lang="es">
<head>
 <meta charset="UTF-8">
 <title>Post</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
 <div class="row">
  <div class="row col s12">
   <div id="post">
   
   </div>
  </div>
 </div>
 <!-- Agregamos la libreria de jQuery -->
 <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
</body>
</html>

Este es el código básico que necesitamos para empezar, pero aun no tenemos nada, antes que nada debemos añadir la función que cargara las entradas, pero de donde?
Crearemos un archivo JSON, yo lo voy a llamar file.json y tendrá la siguiente estructura

[
 {
  "Titulo" : "Conociendo sobre los efectos de transiciones CSS3",
  "Categoria" : "CSS",
  "Fecha" : "03-01-2017",
  "Hora" : "14:55",
  "Permalink" : "https://frikibloggeo.blogspot.com/2017/01/conociendo-sobre-los-efectos-de.html",
  "Autor" : "Anthony Medina",
  "Contenido" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus est ipsam nesciunt? Inventore distinctio hic iusto totam officia sed, veniam eum corporis, repellendus repudiandae, debitis voluptas quos, alias neque porro?"
 },
 {
  "Titulo" : "Menu contextual sencillo con HTML5, CSS3 y JavaScript (jQuery)",
  "Categoria" : "JavaScript",
  "Fecha" : "25-12-2015",
  "Hora" : "17:06",
  "Permalink" : "https://frikibloggeo.blogspot.com/2015/12/menu-contextual-sencillo-con-html5-css3.html",
  "Autor" : "Anthony Medina",
  "Contenido" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas illo esse animi adipisci quia non tempore vero. Voluptatibus modi nesciunt ducimus quibusdam rerum, fugiat quo mollitia facilis, qui quidem veritatis."
 },
 {
  "Titulo" : "Crear tu propio sistema de comentarios con MySQL y PHP",
  "Categoria" : "PHP",
  "Fecha" : "09-06-2016",
  "Hora" : "14:14",
  "Permalink" : "https://frikibloggeo.blogspot.com/2014/06/crear-tu-propio-sistema-de-comentarios.html",
  "Autor" : "Anthony Medina",
  "Contenido" : "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est quas, ea, recusandae laudantium non dolor ad repellat commodi sint? Fugit, voluptas minus aspernatur iste eius atque aliquid recusandae magnam, sunt."
 }
]

Como ya habrás podido notar, un JSON no es mas que un array estructurado mediante un estandar establecido que se puede leer de una manera mas sencilla que cualquier array convencional en cualquier lenguaje, particularmente, en el ejemplo, tenemos un array de JSON cuya longitud presenta 3 objetos, los cuales contienen cierta información sobre entradas de un blog cualquiera como son el titulo, fecha, hora, etc.

Si bien, mirar y leer datos de un archivo JSON ya es humanamente legible por decirlo de alguna manera, no es todavía suficientemente humanamente legible, por el uso de corchetes, comas, llaves, puntos, comillas, etc. Y es que JSON no ha sido creado para ser leído por humanos, ha sido creado para ser consumido por humanos mediante el uso de herramientas con jQuery, AngularJS, PHP, entre muchos otros frameworks y lenguajes.

Ahora, que hacemos con este pedazo de JSON?

Bien, a la estructura HTML anteriormente creada, justo debajo de la CDN de jQuery, pegamos el siguiente codigo

<script type="text/javascript">
            $(document).ready(function() {
                $.ajax({
                    url: "file.json",
                    type: "GET",
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: function() {
                        $('#post').html("Cargando post, por favor, espere");
                    },
                    success: function(response) {
                        $('#post').html("");
                        $.each(response, function(i, post) {
                            $('#post').append(
                                  "<h5 class='row col s12'><a href='"+post.Permalink+"'>"+post.Titulo+"</a></h5>"
                                + "<div class='meta row col s6'>"
                                +      "<span class='chip'>Autor: <b>"+post.Autor+"</b></span>"
                                +      "<span class='chip'>Fecha: <b>"+post.Fecha+"</b></span>"
                                +      "<span class='chip'>Hora: <b>"+post.Hora+"</b></span>"
                                +      "<span class='chip'>Categoria: <b>"+post.Categoria+"</b></span>"
                                + "</div>"
                                + "<p class='row col s12'>"+post.Contenido+"</p>"
                            );
                        });
                    }
                });
            });
    </script> 

Donde podemos observar, tenemos un script cuyo ejecución es realizada al iniciar la pagina mediante el uso de la función $('document').ready(); de jQuery, dentro de ella llamamos a la función $.ajax();, la cual nos hace un llamado a nuestro archivo JSON que anteriormente creamos, enviando una serie de parámetros necesarios para la lectura del mismo, una vez hecho el llamado, la función success de jQuery imprime el callback de la manera mas humanamente legible dentro de nuestro documento HTML.

Que tenemos hasta ahora?


Bien, pasamos de tener un documento en blanco a tener un pagina cargada con post, pero un poco aburrido esos estilos predeterminados?

Que tal si añadimos un poco de magia con materialize? Simplemente, agrega este código de la CDN justo antes de cerrar la etiqueta </head>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">

Eso es todo, mira que bonito se ve ahora, aqui te dejo el codigo completo y una demo del mismo en Plunkr

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Post</title>
    <!-- Agregamos la hoja de Estilos de Materialize (Opcional) -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="row">
        <div class="row col s12">
            <div id="post">
            
            </div>
        </div>
    </div>
    <!-- Agregamos la libreria de jQuery -->
    <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
    <!-- Agregamos la libreria de Materialize (Opcional) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/js/materialize.min.js"></script>
    <!-- Script que se ejecuta al iniciar la pagina y carga los posts a la misma -->
    <script type="text/javascript">
            $(document).ready(function() {
                $.ajax({
                    url: "file.json",
                    type: "GET",
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    beforeSend: function() {
                        $('#post').html("Cargando post, por favor, espere");
                    },
                    success: function(response) {
                        $('#post').html("");
                        $.each(response, function(i, post) {
                            $('#post').append(
                                  "<h5 class='row col s12'><a href='"+post.Permalink+"'>"+post.Titulo+"</a></h5>"
                                + "<div class='meta row col s6'>"
                                +      "<span class='chip waves-effect'>Autor: <b>"+post.Autor+"</b></span>"
                                +      "<span class='chip waves-effect'>Fecha: <b>"+post.Fecha+"</b></span>"
                                +      "<span class='chip waves-effect'>Hora: <b>"+post.Hora+"</b></span>"
                                +      "<span class='chip waves-effect'>Categoria: <b>"+post.Categoria+"</b></span>"
                                + "</div>"
                                + "<p class='row col s12'>"+post.Contenido+"</p>"
                            );
                        });
                    }
                });
            });
    </script>
</body>
</html>

DEMO

Enlaces para compartir en tu blog o pagina web.




Widget por Friki Bloggeo


7 comentarios :

  1. Este comentario ha sido eliminado por un administrador del blog.

    ResponderEliminar
  2. Are you fixing error while setting up two-factor authentication in your Binance account? If you are unable to fix the issue and need some help, you can always call on Binance phone number which is functional all the time and users can talk to the team related Binance Support Number to issue and get tested solutions from the team immediately. Connect with the team through dialing Binance support number which is the key medium to speak to the professionals and discuss your queries.

    ResponderEliminar
  3. Are you unable to work in the Gemini account as you’re going through two-factor functionality issue ? If yes, instead of worrying and pondering about the issue, you can directly have a conversation with the team of skilled professionals who is always there to Gemini Support Number fix your queries. All you have to do is to call on Gemini customer support number which is functional and the team always greets users with positive attitude and fixes all the queries the moment they get them from users.

    ResponderEliminar
  4. Are you unable to sign in to the Binance account? Is this sign in error occur because of some technical issue or you are having hacking attempt in your account? What could be the error possible be? Your main job is to speak to the team and get fruitful results from the team in no time and users can speak to the team anytime to avail solution from the professionals who are always there to fix your queries. All Binance Support Number you have to do is to call on Binance support number and speak to the team related to issue. The team will bring all the accessible steps to fix your issues at the earliest.

    ResponderEliminar
  5. Email address has become the vital a part of a web account as whenever you get into bother of sign language in, you'll be able to continually fix the error by taking facilitate through the e-mail address. If your email address isn't verified already and you're searching for answer to repair it at the earliest, you'll be able to continually take facilitate from the team UN agency is often there to guide you. you've got to appeal Binance support number that is purposeful and users will confer with the team anytime to urge verified solutions in no time. The team is often there to assist you out from each tough scenario.
    More Info Visit Here: https://www.cryptowalletsupport.com/binance-support-number/

    ResponderEliminar
  6. Are you stuck within the middle of commercialism in Gemini and don’t understand what to try and do next ? square measure you unable to shop for and sell Bitcoin in Gemini? To resolve commercialism problems now, you'll be able to take help from the team of specialists World Health Organization is often there to help you. simply take your phone and dial Gemini customer support phone number to get rid of all of your high-level complexities within the least doable time. The well-skilled specialists have all the proper techniques and techniques to subsume the errors.
    For more info visit our website: https://www.cryptowalletsupport.com/gemini-support-number/

    ResponderEliminar
  7. Gemini users get into sign in issues most of the time and the one who are new to this field are unable to deal with this error and face difficulty in opening the account. If you are surrounded by such errors, you are advised to not to waste your time one reaching for solutions and directly contact with the team via calling on Gemini Customer Care Number
    +1833-464-7652 which is always functional and the team is ready to assist you in every possible manner. Talk to the team when you need assistance and get the best possible answers from them.
    For more info visit our website: https://www.geminidesk.com/

    ResponderEliminar