{"id":1566,"date":"2024-08-02T07:24:17","date_gmt":"2024-08-02T05:24:17","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1566"},"modified":"2024-08-02T07:24:17","modified_gmt":"2024-08-02T05:24:17","slug":"002-ajax-objeto-xmlhttprequest","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/15-ajax\/002-ajax-objeto-xmlhttprequest\/","title":{"rendered":"002. AJAX: Objeto XMLHttpRequest"},"content":{"rendered":"\n<p>Como <strong>Ajax<\/strong> trabaja parte con el <strong>cliente<\/strong>, parte con el <strong>servidor<\/strong>, es muy importante que <strong>Ajax<\/strong> lo ejecutemos desde un <strong>servidor web<\/strong>, usando el <strong>protocolo HTTP<\/strong>, no con el protocolo <strong>file<\/strong>, d\u00e1ndole simplemente doble click en el archivo. Hay que comenzar a trabajar en un <strong>entorno local<\/strong>. Vamos a crear una aplicaci\u00f3n donde vamos a consumir una <strong>API externa<\/strong>.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Para poder traer informaci\u00f3n de un servidor (por ejm una petici\u00f3n a una <strong>base de datos<\/strong> o a una <strong>API externa<\/strong>), hay una <strong>API<\/strong> para comenzar a aprender, que se llama <a href=\"https:\/\/jsonplaceholder.typicode.com\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>JSONPlaceholder<\/strong><\/a>, este servicio es una <strong>API<\/strong> falsa para hacer pruebas y prototipos.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Nota<\/strong>: podemos consumir tanto <strong>APIs p\u00fablicas<\/strong> que tengamos en Internet como <strong>archivos JSON<\/strong> que tengamos de manera local.<\/p>\n<\/blockquote>\n\n\n\n<p>Para que un documento <strong>XMLHttpRequest<\/strong> funcione necesitamos dar cuatro pasos:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>La <strong>instancia<\/strong>.<\/li>\n\n\n\n<li>Ejecutar un <strong>evento<\/strong>, el <strong>evento<\/strong> m\u00e1s importante del objeto <strong>XMLHttpRequest<\/strong> es <em><strong>readystatechange<\/strong><\/em>, que detecta el resto de eventos. Por lo que hay que hacer una asignaci\u00f3n del evento o eventos si lo queremos manejar de manera independiente.<\/li>\n\n\n\n<li>La instrucci\u00f3n que va a abrir la petici\u00f3n.<\/li>\n\n\n\n<li>El cuarto paso es enviar la petici\u00f3n.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Resumen<\/h2>\n\n\n\n<p>Los 4 pasos que debemos hacer son:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Instanciar el objeto <strong><em>XMLHttpRequest<\/em><\/strong>.<\/li>\n\n\n\n<li>Asignarle el o los <strong>eventos<\/strong> que vayamos a estar manipulando de la petici\u00f3n, la l\u00f3gica de la programaci\u00f3n va a ir en la <strong>callback<\/strong> de esta fase.<\/li>\n\n\n\n<li>Abrir la petici\u00f3n, estableciendo el m\u00e9todo y el recurso o la <strong>URL<\/strong> o el <strong>endpoint<\/strong> con el m\u00e9todo <strong><em>open()<\/em><\/strong>.<\/li>\n\n\n\n<li>Enviar la petici\u00f3n con el m\u00e9todo <strong><em>sent()<\/em><\/strong>.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Archivos<\/h2>\n\n\n\n<p>Tendremos dos archivos, un archivo ajax.html y un archivo ajax.js, veamos la sintaxis de cada uno de ellos.<\/p>\n\n\n\n<p>Sintaxis de ajax.html<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Ajax&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Ajax&lt;\/h1&gt;\n&nbsp; &nbsp; &lt;h2&gt;Objeto XMLHttpRequest&lt;\/h2&gt;\n&nbsp; &nbsp; &lt;ol id=\"xhr\"&gt;&lt;\/ol&gt;\n&nbsp; &nbsp; &lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;&lt;br \/&gt;\n&nbsp; &nbsp; &lt;script src=\"ajax.js\"&gt;&lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p>Sintaxis de ajax.js<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">(() =&gt; {\n&nbsp; const xhr = new XMLHttpRequest(),\n&nbsp; &nbsp; $xhr = document.getElementById(\"xhr\"),\n&nbsp; &nbsp; $fragment = document.createDocumentFragment();\n&nbsp; xhr.addEventListener(\"readystatechange\", (e) =&gt; {\n&nbsp; &nbsp; if (xhr.readyState !== 4) return;\n\n&nbsp; &nbsp; if (xhr.status &gt;= 200 &amp;&amp; xhr.status &lt; 300) {\n&nbsp; &nbsp; &nbsp; let json = JSON.parse(xhr.responseText);\n&nbsp; &nbsp; &nbsp; json.forEach((el) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; const $li = document.createElement(\"li\");\n&nbsp; &nbsp; &nbsp; &nbsp; $li.innerHTML = `${el.name} -- ${el.email} -- ${el.phone}`;\n &nbsp; &nbsp; &nbsp; $fragment.appendChild($li);\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; $xhr.appendChild($fragment);\n&nbsp; &nbsp; } else {\n&nbsp; &nbsp; &nbsp; console.log(\"Error\");\n&nbsp; &nbsp; &nbsp; let message = xhr.statusText || \"Ocurri\u00f3 un error\";\n&nbsp; &nbsp; &nbsp; $xhr.innerHTML = `Error ${xhr.status}: ${message}`;\n&nbsp; &nbsp; }\n&nbsp; });\n&nbsp; xhr.open(\"GET\", \"https:\/\/jsonplaceholder.typicode.com\/users\");\n&nbsp; xhr.send();\n})();<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Como Ajax trabaja parte con el cliente, parte con el servidor, es muy importante que Ajax lo ejecutemos desde un [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1561,"menu_order":1,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-1566","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"Como Ajax trabaja parte con el cliente, parte con el servidor, es muy importante que Ajax lo ejecutemos desde un [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1566","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=1566"}],"version-history":[{"count":2,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1566\/revisions"}],"predecessor-version":[{"id":1568,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1566\/revisions\/1568"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1561"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=1566"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}