Ver Mensaje Individual
  #3 (permalink)  
Antiguo 10/12/2016, 07:59
mpozo
 
Fecha de Ingreso: noviembre-2015
Mensajes: 231
Antigüedad: 8 años, 5 meses
Puntos: 86
Respuesta: Funciones Callback - Undefined en variable

Aunque la llamada síncrona está desactualizada por que se pierde todo el potencial de ajax, cuando hay que usarla, hay que usarla
Código Javascript:
Ver original
  1. <!DOCTYPE html>
  2. <html dir="ltr" lang="es-es">
  3.     <head>
  4.         <title></title>
  5.         <meta charset="utf-8">
  6.         <meta name="viewport" content="user-scalable=yes, width=device-width, initial-scale=1">
  7.         <style>
  8.  
  9.         </style>
  10.         <script>
  11.             function foo() {
  12.  
  13.                 var usuarios = '{"nombre" : ["Juan", "Pedro", "Mária"]}',
  14.                 url = 'enviojson.php',
  15.                 ajax = new XMLHttpRequest(),
  16.                 u = null;
  17.  
  18.                 ajax.open('POST', url, false);
  19.                 ajax.onreadystatechange = function() {
  20.  
  21.                     if (ajax.readyState == 4) {
  22.  
  23.                         if (ajax.status == 200) {  
  24.  
  25.                             u = ajax.responseText;
  26.                         }
  27.                     }
  28.                 }
  29.                 ajax.setRequestHeader('Content-Type','application/json');  
  30.                 ajax.send(usuarios);
  31.                 return u;
  32.             }
  33.  
  34.  
  35.             var encontrado = foo();
  36.  
  37.             console.log(encontrado);
  38.         </script>
  39.     </head>
  40.     <body>
  41.  
  42.     </body>
  43. </html>
enviojson.php
Código PHP:
Ver original
  1. <?php
  2.  
  3. $content = file_get_contents('php://input');
  4. $dec = json_decode($content, true);
  5. sleep(5);
  6. echo $dec['nombre'][1];
  7.  
  8. ?>