10 - Propiedades onreadystatechange y readystate.
Simulador
(Cuando presiona el botón "ejecutar el programa" se graban todos los cuadros de texto y se ejecuta el primero de la lista mostrando en una página el resultado.
)
Implementar una aplicación que calcule el cuadrado de un número que ingresamos por teclado. Y además mostrar mediante un alert el estado actual de la propiedad readyState del objeto XMLHttpRequest.
pagina1.html
<html> <head> <title>Problema</title> <script src="funciones.js" language="JavaScript"></script> </head> <body> <form action="pagina1.php" method="post" id="formulario"> Ingrese nro:<input type="text" name="nro" id="nro" size="10"><br> <input type="submit" value="Calcular el cuadrado" id="enviar"> <div id="resultados"></div> </form> </body> </html>
funciones.js
addEvent(window,'load',inicializarEventos,false); function inicializarEventos() { var ref=document.getElementById('formulario'); addEvent(ref,'submit',enviarDatos,false); } function enviarDatos(e) { if (window.event) window.event.returnValue=false; else if (e) e.preventDefault(); enviarFormulario(); } var conexion1; function enviarFormulario() { conexion1=crearXMLHttpRequest(); conexion1.onreadystatechange = procesarEventos; var num=document.getElementById('nro').value; alert('Valor de la propiedad readyState:'+conexion1.readyState); conexion1.open('GET','pagina1.php?numero='+num, true); conexion1.send(null); } function procesarEventos() { alert('Valor de la propiedad readyState:'+conexion1.readyState); var resultados = document.getElementById("resultados"); if(conexion1.readyState == 4) { resultados.innerHTML = conexion1.responseText; } else if (conexion1.readyState==1 || conexion1.readyState==2 || conexion1.readyState==3) { resultados.innerHTML = 'Procesando...'; } } //*************************************** //Funciones comunes a todos los problemas //*************************************** function addEvent(elemento,nomevento,funcion,captura) { if (elemento.attachEvent) { elemento.attachEvent('on'+nomevento,funcion); return true; } else if (elemento.addEventListener) { elemento.addEventListener(nomevento,funcion,captura); return true; } else return false; } function crearXMLHttpRequest() { var xmlHttp=null; if (window.ActiveXObject) xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); return xmlHttp; }
pagina1.php
<?php $cuadrado=$_REQUEST['numero']*$_REQUEST['numero']; echo $cuadrado; ?>