Ver Mensaje Individual
  #1 (permalink)  
Antiguo 02/10/2011, 11:59
agcforos
 
Fecha de Ingreso: julio-2011
Mensajes: 91
Antigüedad: 12 años, 9 meses
Puntos: 2
¿Es incompatible responseText de ajax con JSON?

Hola.
Estoy realizando una petición ajax y me esta devolviendo una cadena pero no consigo leer nada de esta cadena, sin duda porque estoy haciendo . En el php en el que hago la petición en el servidor, paso la consulta a JSON y previamente he pasado esta consulta a un array para poder leerlo con javascript.
En resumen:
1 - Realizo la petición AJAX.
2 - Hago la consulta en el php.
3 - Transformo esta consulta a un array
4 - Trato este array mediante una función para poder leer estos datos con javascript.
5 - Codifico este array con JSON para transmitirlo.
6 - Lo recibo en el html con javascript.
7 - A partir de aquí me vienen las muchas dudas. Si lo intento descodificar para poder leerlo, el javascript me da un error en el momento que pongo JSON.parse.

¿Esto último se puede dar porque no se puede pasar el JSON codificado como una cadena de texto con responseText?

Adjunto el código por si alguien puede ayudarme y decirme como leer los elementos de este imagino que array.


Código Javascript:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  3.  
  4. <head>
  5.     <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  6.     <meta name="author" content="SyToo" />
  7.    
  8.     <script type="text/javascript" src="json.js"></script>  
  9.     <script type="text/javascript">
  10.  
  11.     var title1;
  12.     var idcurso;
  13.     var idasignatura;
  14.     var idtema;
  15.     var curso;
  16.     var asignatura;
  17.     var tema;
  18.     var usuario;
  19.     var myArr;
  20.     var capaContenedora;
  21.    
  22.     function inicio(){
  23.         var vars=[];
  24.         query=window.location.search.substring(1);
  25.         q=query.split("&");
  26.         for(i=0;i<q.length;i++){
  27.             x=q[i].split("=");
  28.             k=x[0];
  29.             v=x[1];
  30.             vars[k]=v;
  31.         }
  32.         idcurso = vars['idcurso'];
  33.         idasignatura = vars['idasignatura'];
  34.         curso = vars['curso'];
  35.         asignatura = vars['asignatura'];
  36.         tema = vars['tema'];
  37.         idtema = vars['idtema'];
  38.         usuario = vars['usuario'];
  39.         title1 = curso+' - '+asignatura+' - '+tema;
  40.         document.title = unescape(title1);
  41.         verCabecera();
  42.         verUsuario();
  43.         FAjax('devuelveArray.php', 'capaContenedora', 'idtema='+idtema, 'POST');
  44.     }
  45.    
  46.     function verCabecera(){
  47.         document.getElementById('cat').innerHTML = unescape(title1);
  48.     }
  49.    
  50.     function verUsuario(){
  51.         document.getElementById('usu').innerHTML = unescape(usuario);
  52.     }
  53.      
  54.     function creaAjax(){
  55.         var objetoAjax = false;
  56.         try {
  57.             // Para navegadores distintos a Internet Explorer.
  58.             objetoAjax = new ActiveXObject("Msxml2.XMLHTTP");
  59.         } catch (e) {
  60.             try {
  61.                 // Para Explorer.
  62.                 objetoAjax = new ActiveXObject("Microsoft.XMLHTTP");
  63.             }
  64.             catch (E) {
  65.                 objetoAjax = false;
  66.             }
  67.         }
  68.         if(!objetoAjax && typeof XMLHttpRequest != 'undefined') {
  69.             objetoAjax = new XMLHttpRequest();
  70.         }
  71.         return objetoAjax;
  72.     }
  73.    
  74.     function FAjax(url, capa, valores, metodo){
  75.         var ajax = creaAjax();
  76.        
  77.         //Creamos y ejecutamos la instancia si el método elegido es POST.
  78.         if (metodo.toUpperCase() == 'POST') {
  79.             ajax.open('POST', url, true);
  80.             ajax.onreadystatechange = function(){
  81.                 procesaAjax(ajax, capa);
  82.             }
  83.             ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  84.             ajax.send(valores);
  85.             return;
  86.         }
  87.        
  88.         //Creamos y ejecutamos la instancia si el método elegido es GET.
  89.         if (metodo.toUpperCase() == 'GET') {
  90.             ajax.open('GET', url, true);
  91.             ajax.onreadystatechange = function(){
  92.                 procesaAjax(ajax, capa);
  93.             }
  94.             ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  95.             ajax.send(null);
  96.             return;    
  97.         }
  98.     }
  99.    
  100.     function procesaAjax(ajax, capa){
  101.         capaContenedora = document.getElementById(capa);
  102.         if (ajax.readyState == 1) {
  103.                 capaContenedora.innerHTML = "Cargando.......";
  104.         } else if (ajax.readyState == 4) {
  105.             if (ajax.status == 200) {
  106.                 myArr = replaceAll(ajax.responseText, '|', '"');
  107.                 //capaContenedora.innerHTML = myArr;
  108.                 procesarArray();              
  109.             } else if (ajax.status == 404) {
  110.                 capaContenedora.innerHTML = "La dirección no existe";
  111.             } else {
  112.                 capaContenedora.innerHTML = "Error: " + ajax.status;
  113.             }
  114.         }
  115.     }
  116.    
  117.     function procesarArray(){
  118.         myArray = JSON.parse(myArr);
  119.         capaContenedora.innerHTML = myArray;
  120.     }
  121.    
  122.     function replaceAll( text, busca, reemplaza ){
  123.         while (text.toString().indexOf(busca) != -1) {         
  124.           text = text.toString().replace(busca,reemplaza);
  125.     }
  126.         return text;
  127.     }
  128.  
  129.    
  130.    
  131.    
  132. </script>
  133.  
  134.     <title></title>
  135.    
  136. <style>
  137.       h2 {
  138.         font-family: Arial, Helvetica, sans-serif;
  139.         font-size: 22px;
  140.         color : red;
  141.         margin : 6px;
  142.       }
  143.       body {
  144.         font-family: Arial, Helvetica, sans-serif;
  145.         font-size: 13px;
  146.         background-color: #F5DEB3;
  147.       }
  148.       li, td {
  149.         font-family: Arial, Helvetica, sans-serif;
  150.         font-size: 13px;
  151.       }
  152.       hr {
  153.         color: #FF0000;
  154.         width:70%;
  155.         text-align:center;
  156.       }
  157.       a {
  158.         color: #000000
  159.       }
  160.       input.error{
  161.         background-color : silver;
  162.         border : 1px solid black;
  163.       }
  164.       #volver, #pregunta{
  165.         text-align:center;
  166.       }
  167.       #pregunta, #respuesta1, #respuesta2, #respuesta3, #respuesta4{
  168.         padding-left: 7px;
  169.       }
  170.       #capaContenedora{
  171.         border-style: groove double;
  172.         padding: 10px;
  173.         margin: 14px;
  174.         border-color: blue;
  175.       }
  176. </style>
  177.    
  178. </head>
  179.  
  180. <body>
  181.  
  182.     <table width=100% border=0 cellspacing = 0 background='imagenes/indice1.jpg'>
  183.         <tr>
  184.         <td rowspan = 2>
  185.         <a href = "do_cursos.php"><img src="imagenes/libro.png" alt="Anagrama Aprendetu" border=0
  186.              align=left valign=bottom height = 60 width = 247></a>
  187.         </td>
  188.         <td align = right valign = bottom>
  189.          
  190.         </td>
  191.         </tr>
  192.     </table>
  193.    
  194.     <h2 id='cat'></h2>
  195.      
  196.     Tu usuario es: <b id='usu'></b>
  197.    
  198.     Este es el ejemplo de envío recepción de datos por AJAX<br /><br />
  199.     <!--<div style="text-align: center;">
  200.         <form method="post" onsubmit="FAjax('devuelveArray.php', 'capaContenedora', 'idtema='+idtema, 'POST'); return false" action="#">
  201.             <input type="hidden" id="idtema" value="" />
  202.             <div><input type="submit" value="enviar" /></div>
  203.         </form>
  204.     </div>-->
  205.     <div id="capaContenedora">Capa que recibirá los datos</div>
  206.  
  207. <script>
  208. // Recupero los parámetros de entrada y cargo el campo oculto idtema.
  209.     inicio();
  210.     //document.getElementById('curso').value = idcurso;
  211. </script>
  212. </body>
  213. </html>


Código PHP:
Ver original
  1. <?
  2.   include ('aprendetu_sc_fns.php');
  3.   // Necesitamos una sesión, así que empezar una
  4.  
  5.   ?>
  6.  
  7.         <LINK rel="stylesheet" type="text/css" href="cuerpo.css">
  8.      
  9.   <?php
  10.  
  11.   $array_preguntas = array();
  12.    
  13.   $idtema = $_POST['idtema'];
  14.  
  15.   // Obtener las preguntas relacionadas con el tema seleccionado
  16.   $preguntas = get_preguntas($idtema);
  17.  
  18.   $numero_preguntas = @mysql_num_rows($preguntas);
  19.  
  20.   $usuario = $_SESSION['usuario'];
  21.   $_SESSION['num_preguntas'] = $numero_preguntas;
  22.   $_SESSION['indice_array'] = 0;
  23.   $_SESSION['aciertos'] = 0;
  24.   $_SESSION['primeraVez'] = true;
  25.  
  26.   if ($numero_preguntas > 0){
  27.       // Array que contendrá las filas de nuestra consulta
  28.     for($i=0; $i<$numero_preguntas; $i++) {  
  29.         $array_preguntas[$i] = mysql_fetch_array($preguntas);
  30.     }
  31.    
  32.     PHPtoJS($array_preguntas);
  33.     $oJSON = new JSON();
  34.     $myArr = $oJSON->encode($array_preguntas);
  35.     $myArr = str_replace('"','|',$myArr);
  36.     //echo "valor de myArr: ".$myArr;
  37.    
  38.     if ($_GET) {
  39.        echo "Valores del formulario con el método GET: <pre>";
  40.        print_r($myArr);
  41.        echo "</pre>";
  42.     }
  43.     if ($_POST) {
  44.        echo "Valores del formulario con el método POST: <pre>";
  45.        print_r($myArr);
  46.        echo "</pre>";
  47.     }
  48.    
  49. } else {
  50.     echo "<p>Este tema actualmente no tiene preguntas/respuestas a realizar</p>";
  51.   }
  52. ?>


Dentro del anterior include está el include_once("JSON.php");


Muchas gracias a todos y saludos.