Diferencia entre revisiones de «Usuario:ManuelRomero/ProgramacionWeb/Distancia2018/Jaxon/conceptos»
De WikiEducator
(→Usando jaxon en nuestro proyecto) |
|||
| Línea 59: | Línea 59: | ||
*Si hacemos un click realizaremos una llamada ajax para que nos visualice el contenido de la caja de texto en máyúscula | *Si hacemos un click realizaremos una llamada ajax para que nos visualice el contenido de la caja de texto en máyúscula | ||
}} | }} | ||
| + | *Para proceder en este proyecto hemos de implementar acciones tanto en el cliente como en el servidor | ||
| + | *Este planteaminto es genérico o común independientemente de lo que usemos para construir el escenario ''''ajax'''' | ||
| + | 1.-La parte del servidor | ||
| + | 2.-La parte del cliente | ||
| + | ====La parte del servidor==== | ||
| + | ;Iniciamos el objeto jaxon para preparar el entorno | ||
| + | ====La parte del cliente==== | ||
| + | ;Usando jaxon para escribir script en el cliente para que funcione la solicitud ajax | ||
| + | |||
| + | {{MRM_Actividad|Title=1.-creamos el objeto jaxon| | ||
| + | <source lang=php> | ||
| + | <?php | ||
| + | //Usamos composer para cagar los ficheros necesarios para usar los métodos de diferentes clases | ||
| + | require_once "vendor/autoload.php"; | ||
| + | |||
| + | // Obtenemos un objeto de la clase jaxon a traveś de un método que nos devuelve un objeto jaxon | ||
| + | $jaxon = jaxon(); //método ubicado en el fichero vendor/jaxon-php/jaxon-core/src/start.php | ||
| + | ?> | ||
| + | </source> | ||
| + | }} | ||
| + | {{MRM_Actividad|Title=2.-Cargamos estilos de jaxon (opcional)| | ||
| + | *En el html, mejor en cabecera cargamos los estilos propios de jaxon | ||
| + | <source lang=html5> | ||
| + | <html lang="en"> | ||
| + | <head> | ||
| + | <meta charset="UTF-8"> | ||
| + | <meta name="viewport" | ||
| + | content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | ||
| + | <meta http-equiv="X-UA-Compatible" content="ie=edge"> | ||
| + | <title>Document</title> | ||
| + | <?=$jaxon->getCss() // Insert the Jaxon CSS code into the page?> | ||
| + | </head> | ||
| + | </source> | ||
| + | }} | ||
| + | {{MRM_Actividad|Title=3.-Escribimos el código javascript para enviar las solicitudes XMLHttpRequest| | ||
| + | *En el html, mejor en cabecera cargamos los estilos propios de jaxon | ||
| + | <source lang=html5> | ||
| + | ..... | ||
| + | </body> | ||
| + | <?php | ||
| + | // Insert the Jaxon javascript code into the page | ||
| + | echo $jaxon->getJs(); | ||
| + | echo $jaxon->getScript(); | ||
| + | ?> | ||
| + | </body> | ||
| + | </source> | ||
| + | }} | ||
| + | *Si ejecutamos ahora el proyecto vemos que no sale nada ya que no hemos generado ninguna salida | ||
| + | *Sin embargo si vemos el código fuente, podremos ver todo el código | ||
| + | <source lang=php> | ||
| + | <?php | ||
| + | /** | ||
| + | * Created by PhpStorm. | ||
| + | * User: manuel | ||
| + | * Date: 15/04/19 | ||
| + | * Time: 16:57 | ||
| + | */ | ||
| + | require_once "vendor/autoload.php"; | ||
| + | // Obtenemos un objeto de la clase jaxon a traveś de un método que nos devuelve un objeto jaxon | ||
| + | $jaxon = jaxon(); | ||
| + | ?> | ||
| + | |||
| + | <!doctype html> | ||
| + | <html lang="en"> | ||
| + | <head> | ||
| + | <meta charset="UTF-8"> | ||
| + | <meta name="viewport" | ||
| + | content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | ||
| + | <meta http-equiv="X-UA-Compatible" content="ie=edge"> | ||
| + | <title>Document</title> | ||
| + | <?=$jaxon->getCss() //<!-- // Insert the Jaxon CSS code into the page?> | ||
| + | </head> | ||
| + | <body> | ||
| + | <?php | ||
| + | // Insert the Jaxon javascript code into the page | ||
| + | echo $jaxon->getJs(); | ||
| + | echo $jaxon->getScript(); | ||
| + | ?> | ||
| + | </body> | ||
| + | </html> | ||
| + | </source> | ||
| + | *Genera la siguiente salida | ||
| + | {{Plegable|hide|Código html de la página que ejecuta el códgio anterior| | ||
| + | <source lang=php> | ||
| + | |||
| + | <!doctype html> | ||
| + | <html lang="en"> | ||
| + | <head> | ||
| + | <meta charset="UTF-8"> | ||
| + | <meta name="viewport" | ||
| + | content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | ||
| + | <meta http-equiv="X-UA-Compatible" content="ie=edge"> | ||
| + | <title>Document</title> | ||
| + | |||
| + | </head> | ||
| + | <body> | ||
| + | <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/jaxon-php/jaxon-js@2.0/dist/jaxon.core.min.js" charset="UTF-8"></script> | ||
| + | |||
| + | <script type="text/javascript" charset="UTF-8"> | ||
| + | /* <![CDATA[ */ | ||
| + | try { | ||
| + | if(typeof jaxon.config == undefined) | ||
| + | jaxon.config = {}; | ||
| + | } | ||
| + | catch(e) { | ||
| + | jaxon = {}; | ||
| + | jaxon.config = {}; | ||
| + | }; | ||
| + | |||
| + | jaxon.config.requestURI = "http://localhost/ajax1/"; | ||
| + | jaxon.config.statusMessages = false; | ||
| + | jaxon.config.waitCursor = true; | ||
| + | jaxon.config.version = "Jaxon 2.2.4"; | ||
| + | jaxon.config.defaultMode = "asynchronous"; | ||
| + | jaxon.config.defaultMethod = "POST"; | ||
| + | jaxon.config.responseType = "JSON"; | ||
| + | |||
| + | jaxon.confirm = { | ||
| + | skip: function(command) { | ||
| + | numberOfCommands = command.id; | ||
| + | while (0 < numberOfCommands) { | ||
| + | jaxon.tools.queue.pop(command.response); | ||
| + | --numberOfCommands; | ||
| + | } | ||
| + | } | ||
| + | }; | ||
| + | /* | ||
| + | Function: jaxon.confirm.commands | ||
| + | |||
| + | A rewrite of the jaxon.confirm.commands function which uses the user configured confirm library. | ||
| + | |||
| + | Parameters: | ||
| + | command (object) - jaxon response object | ||
| + | |||
| + | Returns: | ||
| + | true - The operation completed successfully. | ||
| + | */ | ||
| + | jaxon.confirm.commands = function(command) { | ||
| + | command.fullName = 'confirmCommands'; | ||
| + | var msg = command.data; | ||
| + | /* | ||
| + | * Unlike javascript confirm(), third party confirm() functions are not blocking. | ||
| + | * Therefore, to prevent the next commands to run while the library is waiting for the user confirmation, | ||
| + | * the remaining commands are moved to a new queue in the command object. | ||
| + | * They will be processed in the confirm callbacks. | ||
| + | * Note that only one confirm command will be allowed in a Jaxon response. | ||
| + | */ | ||
| + | command.response = jaxon.tools.queue.create(jaxon.config.responseQueueSize); | ||
| + | while((obj = jaxon.tools.queue.pop(jaxon.response)) != null) | ||
| + | { | ||
| + | jaxon.tools.queue.push(command.response, obj); | ||
| + | delete obj; | ||
| + | } | ||
| + | if(confirm(msg)){jaxon.ajax.response.process(command.response);}else{jaxon.confirm.skip(command);jaxon.ajax.response.process(command.response);}; | ||
| + | return true; | ||
| + | }; | ||
| + | |||
| + | jaxon.dom.ready(function() { | ||
| + | jaxon.command.handler.register('cc', jaxon.confirm.commands); | ||
| + | |||
| + | |||
| + | jaxon.command.handler.register("jquery", function(args) { | ||
| + | jaxon.cmd.script.execute(args); | ||
| + | });}); | ||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| + | /* ]]> */ | ||
| + | </script> | ||
| + | </body> | ||
| + | </html> | ||
| + | |||
| + | </source> | ||
| − | |||
| − | |||
}} | }} | ||
Revisión de 17:57 15 abr 2019
| Trabajo en proceso, espera cambios frecuentes. Tu ayuda y retroalimentación son bienvenidos. Ver página de charlas. |
Contenido
Qué es Ajax
AJAX, siglas que referncian a JavaScript y XML Asíncrono.
|
- En el proceso vemos que hay una serie de pasos o acciones
- Cliente solicita algo (evento javascript que hace una solicitud al servidor)
- El servidor recibe la solicitud y empaqueta datos en formato xml que entrega al cliente
- El cliente recibe los datos y con ellos se actualiza parte de la página
- En la imagen siguiente podemos ver el proceso de la relaciónentre cliente y servidor
Dónde se espcefician el código para que esto funcione
- Realmente esta es una cuestión que hay que pensar un momento para no crear confusión
Siempre que usemos esta tecnología necesitamos que los mismos elementos estén en acción
|
- Este escenario lo podemos implementar con diferentes tecnologías.
- Como hemos visto anteriormente lo que nos faltaría es saber como se comunia cliente servidor y servidor cliente para enviar/recibir la solicud/datos
- Como vemos en la imagen la comunicación entre cliente y servidor utiliza un objeto XMLHttpRequest
- Para facilitar el trabajo de acceder directamente al objeto, se utilizan framework como nos ofrece jquery, react, vue, ...
- También hay librerías que desde php podemos establecer este escenario
- Nosotros vamos a hacerlo con jaxon una librería que actualiza xajax proyecto que se abandonó ante la nueva versión de php 7.x
Jaxon=
- La página la tenemos en
- Una vez instalado vemos que en el directorio actual ha creado una carpeta jaxon-php/jaxon-core donde se ubica todos los fuentes de nuestra librería
- Vamos a ver su funcionamiento práctico, si bien tenemos muchas funcionalidades incluso podemos usar jquery como un método del objeto jaxon, pero para eso, personalmente pienso que es mejor usar jquery o bien nuevos y más potentes framworks como Vue o React.
Usando jaxon en nuestro proyecto
- Vamos a separar todo en ficheros independientes
- Para proceder en este proyecto hemos de implementar acciones tanto en el cliente como en el servidor
- Este planteaminto es genérico o común independientemente de lo que usemos para construir el escenario 'ajax'
1.-La parte del servidor 2.-La parte del cliente
La parte del servidor
- Iniciamos el objeto jaxon para preparar el entorno
La parte del cliente
- Usando jaxon para escribir script en el cliente para que funcione la solicitud ajax
<?php //Usamos composer para cagar los ficheros necesarios para usar los métodos de diferentes clases require_once "vendor/autoload.php"; // Obtenemos un objeto de la clase jaxon a traveś de un método que nos devuelve un objeto jaxon $jaxon = jaxon(); //método ubicado en el fichero vendor/jaxon-php/jaxon-core/src/start.php ?>
|
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <?=$jaxon->getCss() // Insert the Jaxon CSS code into the page?> </head>
|
- Si ejecutamos ahora el proyecto vemos que no sale nada ya que no hemos generado ninguna salida
- Sin embargo si vemos el código fuente, podremos ver todo el código
<?php /** * Created by PhpStorm. * User: manuel * Date: 15/04/19 * Time: 16:57 */ require_once "vendor/autoload.php"; // Obtenemos un objeto de la clase jaxon a traveś de un método que nos devuelve un objeto jaxon $jaxon = jaxon(); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <?=$jaxon->getCss() //<!-- // Insert the Jaxon CSS code into the page?> </head> <body> <?php // Insert the Jaxon javascript code into the page echo $jaxon->getJs(); echo $jaxon->getScript(); ?> </body> </html>
- Genera la siguiente salida
| Código html de la página que ejecuta el códgio anterior |
|---|
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/jaxon-php/jaxon-js@2.0/dist/jaxon.core.min.js" charset="UTF-8"></script> <script type="text/javascript" charset="UTF-8"> /* <![CDATA[ */ try { if(typeof jaxon.config == undefined) jaxon.config = {}; } catch(e) { jaxon = {}; jaxon.config = {}; }; jaxon.config.requestURI = "http://localhost/ajax1/"; jaxon.config.statusMessages = false; jaxon.config.waitCursor = true; jaxon.config.version = "Jaxon 2.2.4"; jaxon.config.defaultMode = "asynchronous"; jaxon.config.defaultMethod = "POST"; jaxon.config.responseType = "JSON"; jaxon.confirm = { skip: function(command) { numberOfCommands = command.id; while (0 < numberOfCommands) { jaxon.tools.queue.pop(command.response); --numberOfCommands; } } }; /* Function: jaxon.confirm.commands A rewrite of the jaxon.confirm.commands function which uses the user configured confirm library. Parameters: command (object) - jaxon response object Returns: true - The operation completed successfully. */ jaxon.confirm.commands = function(command) { command.fullName = 'confirmCommands'; var msg = command.data; /* * Unlike javascript confirm(), third party confirm() functions are not blocking. * Therefore, to prevent the next commands to run while the library is waiting for the user confirmation, * the remaining commands are moved to a new queue in the command object. * They will be processed in the confirm callbacks. * Note that only one confirm command will be allowed in a Jaxon response. */ command.response = jaxon.tools.queue.create(jaxon.config.responseQueueSize); while((obj = jaxon.tools.queue.pop(jaxon.response)) != null) { jaxon.tools.queue.push(command.response, obj); delete obj; } if(confirm(msg)){jaxon.ajax.response.process(command.response);}else{jaxon.confirm.skip(command);jaxon.ajax.response.process(command.response);}; return true; }; jaxon.dom.ready(function() { jaxon.command.handler.register('cc', jaxon.confirm.commands); jaxon.command.handler.register("jquery", function(args) { jaxon.cmd.script.execute(args); });}); /* ]]> */ </script> </body> </html>
|



