Ver Mensaje Individual
  #7 (permalink)  
Antiguo 26/04/2014, 09:12
bathorz
 
Fecha de Ingreso: agosto-2013
Mensajes: 150
Antigüedad: 11 años, 6 meses
Puntos: 29
Respuesta: A vueltas con el Ajax

Asignar un valor y comentar $_POST['numero'] para una prueba, nada más.
El número aleatorio se generaba cada vez, correcto. Ahora ya no.
Conservar el valor lo he hecho en el php, puedes buscar otro modo.

Esta es una forma entre tantas de hacerlo funcionar. Luego afinas, corriges, cambias a gusto.

Código Javascript:
Ver original
  1. window.onload = function() {
  2.  
  3.         function ajax(url, datos) {
  4.           var oAjax;
  5.           if (window.XMLHttpRequest) {
  6.             oAjax = new XMLHttpRequest();
  7.           } else {
  8.             oAjax = new ActiveXObject("Microsoft.XMLHTTP");
  9.           }
  10.           oAjax.open("POST", url, true);
  11.           oAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  12.           oAjax.send(datos);
  13.  
  14.           oAjax.onreadystatechange = function() {
  15.             if (oAjax.readyState === 4 && oAjax.status === 200) {
  16.               rta.innerHTML = oAjax.responseText;
  17.             }
  18.           };
  19.         }
  20.  
  21.         var rta = document.getElementById("rta");
  22.         var boton = document.getElementById('boton');
  23.  
  24.         boton.addEventListener('click', function(e) {
  25.           var cadena = 'numero=' + document.getElementById('numero').value;
  26.           ajax('adivina.php', cadena);
  27.         });
  28.  
  29.       };
Código HTML:
Ver original
  1. Adivina entre 1 y 10
  2.     <input type="number" name="numero" id="numero" />
  3.     <button id="boton">boton</button>
  4.     <div id="rta">Rta.</div>

adivina.php
Código PHP:
Ver original
  1. if (!$numero) {
  2.   $numero = $_POST['numero'];
  3.   $aleatorio = rand(1, 10);
  4. }
  5.  
  6. $html = $numero;
  7. switch (true) {
  8.   case ($numero == ''):
  9.     echo " Falta número ";
  10.     exit;
  11.   case ($numero == $aleatorio):
  12.     $html .= " Acertaste ";
  13.     break;
  14.   case ($numero > $aleatorio):
  15.     $html .= " Te has pasado ";
  16.     break;
  17.   default:
  18.     $html .= " Te quedas corto ";
  19.     break;
  20. }
  21. $html .= $aleatorio;
  22. echo $html;