Foros del Web » Programando para Internet » Javascript »

SyntaxError: Unexpected token <

Estas en el tema de SyntaxError: Unexpected token < en el foro de Javascript en Foros del Web. Hola, que tal? Estoy teniendo un problema con JSON, me sale el error del titulo: "SyntaxError: Unexpected token <" Alguien sabe porque podria ser?, necesitan ...
  #1 (permalink)  
Antiguo 27/08/2011, 03:10
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 9 meses
Puntos: 8
SyntaxError: Unexpected token <

Hola, que tal?

Estoy teniendo un problema con JSON, me sale el error del titulo: "SyntaxError: Unexpected token <"

Alguien sabe porque podria ser?, necesitan de mi codigo para poder identificar el error o es un error ya conocido?

Gracias!
  #2 (permalink)  
Antiguo 27/08/2011, 03:42
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Respuesta: SyntaxError: Unexpected token <

Hola:

JSON es javascript, por eso movemos el tema desde Ajax. Sobre el error, sin más código no se puede adivinar, pero tal vez si miras la consola de errores del navegador sepas solucionarlo (procura ver tus páginas en distintos navegadores, y busca la consola de error o de javascript.

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #3 (permalink)  
Antiguo 27/08/2011, 05:11
Avatar de _cronos2
Colaborador
 
Fecha de Ingreso: junio-2010
Mensajes: 2.062
Antigüedad: 13 años, 10 meses
Puntos: 310
Respuesta: SyntaxError: Unexpected token <

Si estás usando algún hosting gratuito es posible que te peguen al request algún texto propio de ellos, a mí me pasa en miarroba al cargar .js y en los responseText, así que es posible que en JSON también ocurra.
Saludos (:
__________________
" Getting older’s not been on my plans
but it’s never late, it’s never late enough for me to stay. "
Cigarettes - Russian Red
  #4 (permalink)  
Antiguo 27/08/2011, 13:01
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 9 meses
Puntos: 8
Respuesta: SyntaxError: Unexpected token <

Este es mi codigo, sigo sin poder encontrar el problema, en distintos exploradores me bota un error distinto:

En Google Chrome: SyntaxError: Unexpected token <
En Windows Internet Explorer 9: SyntaxError: Syntax error
En Mozila Firefox: SyntaxError: invalid regular expression flag b

ver.php:

Código Javascript:
Ver original
  1. <?php
  2.     mysql_connect('localhost','usuario','contraseña');
  3.     mysql_select_db('rutas');
  4.    
  5.     $query = mysql_query("SELECT * FROM mapdir");
  6. ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  7. <html xmlns="http://www.w3.org/1999/xhtml">
  8. <head>
  9. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  10. <title>Ver Ruta</title>
  11. </head>
  12.  
  13.  
  14. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
  15. <script src="js/jquery-1.4.3.min.js"></script>
  16. <style type="text/css">
  17.     #address{
  18.         float:left;
  19.         width:300px;
  20.         margin-left:10px;
  21.         border:2px dashed #F5F5F5;
  22.         padding:0 20px 20px 20px
  23.     }
  24.     #address ul{
  25.         padding:0;
  26.         list-style:none
  27.     }
  28.     #address ul li{
  29.         height: auto;
  30.         width: 300px;
  31.         -moz-border-radius: 4px;
  32.         border-radius: 4px;
  33.         background:#F9F9F9;
  34.         padding:6px
  35.     }
  36.     #address ul li a{
  37.         padding:0;
  38.         font:normal 11px Verdana, Geneva, sans-serif;
  39.         color:#03C
  40.     }
  41.     h2{
  42.         font:normal 16px Tahoma, Geneva, sans-serif;
  43.         color:#900
  44.     }
  45. </style>
  46. <body onLoad="goma()">
  47. <div id="mappy" style="width:800px; height:550px; float:left"></div>
  48. <div id="address">
  49.  
  50.     <h2>Rutas Generadas</h2>
  51.     <ul>
  52.         <?php
  53.         while($row = mysql_fetch_array($query)){
  54.             ?>
  55.             <li><a href="ver.php?id=<?php echo $row['id']?>"><?php echo $row['origen']." - ".$row['destino'] ?> </a></li>
  56.             <?php
  57.         }
  58.         ?>
  59.     </ul>
  60. </div>
  61.  
  62. <script>
  63. var map, ren, ser;
  64. var data = {};
  65. function goma()
  66. {
  67. map = new google.maps.Map( document.getElementById('mappy'), {'zoom':12, 'mapTypeId': google.maps.MapTypeId.ROADMAP, 'center': new google.maps.LatLng(-12.1008684,-77.0288967) })
  68.  
  69.     ren = new google.maps.DirectionsRenderer( {'draggable':true} );
  70.     ren.setMap(map);
  71.     ser = new google.maps.DirectionsService();
  72.     fetchdata()
  73. }
  74.  
  75. function setroute(os)
  76. {
  77.     var wp = [];
  78.     for(var i=0;i<os.waypoints.length;i++)
  79.         wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
  80.        
  81.     ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
  82.     'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
  83.     'waypoints': wp,
  84.     'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
  85.         if(sts=='OK')ren.setDirections(res);
  86.     }) 
  87. }
  88.  
  89. function fetchdata()
  90. {  
  91.     $.post("process.php",{command:'fetch', id:'<?php echo $_GET['id'] ?>'},function(data){
  92.         try { setroute( eval('(' + data + ')') ); }
  93.         catch(e){ alert(e); }
  94.     });
  95. }
  96. </script>
  97. </body>
  98. </html>


process.php
Código PHP:
<?php
    ob_start
(); header('Cache-Control: no-store, no-cache, must-revalidate');

    
$data $_REQUEST['mapdata'];
    
    
mysql_connect('localhost','usuario','contraseña');
    
mysql_select_db('rutas');
    
    if(
$_REQUEST['command']=='save')
    {
        
        
$query "INSERT INTO mapdir VALUES('','".$_POST['origen']."','".$_POST['destino']."','".$data."')";
        if(
mysql_query($query)) echo "bien-".mysql_insert_id();
        die(
mysql_error());
    }
    
    if(
$_REQUEST['command']=='fetch')
    {
        
$query "SELECT value FROM mapdir WHERE id = '".$_POST['id']."'";
        if(!(
$res mysql_query($query)))die(mysql_error());        
        
$rs mysql_fetch_array($res,1);
        die(
$rs['value']);        
    }
?>
Continua...
  #5 (permalink)  
Antiguo 27/08/2011, 13:02
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 9 meses
Puntos: 8
Respuesta: SyntaxError: Unexpected token <

json2.js
Código Javascript:
Ver original
  1. if (!this.JSON) {
  2.     JSON = {};
  3. }
  4. (function () {
  5.  
  6.     function f(n) {
  7.         return n < 10 ? '0' + n : n;
  8.     }
  9.  
  10.     if (typeof Date.prototype.toJSON !== 'function') {
  11.  
  12.         Date.prototype.toJSON = function (key) {
  13.  
  14.             return this.getUTCFullYear()   + '-' +
  15.                  f(this.getUTCMonth() + 1) + '-' +
  16.                  f(this.getUTCDate())      + 'T' +
  17.                  f(this.getUTCHours())     + ':' +
  18.                  f(this.getUTCMinutes())   + ':' +
  19.                  f(this.getUTCSeconds())   + 'Z';
  20.         };
  21.  
  22.         String.prototype.toJSON =
  23.         Number.prototype.toJSON =
  24.         Boolean.prototype.toJSON = function (key) {
  25.             return this.valueOf();
  26.         };
  27.     }
  28.  
  29.     var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  30.         escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
  31.         gap,
  32.         indent,
  33.         meta = {
  34.             '\b': '\\b',
  35.             '\t': '\\t',
  36.             '\n': '\\n',
  37.             '\f': '\\f',
  38.             '\r': '\\r',
  39.             '"' : '\\"',
  40.             '\\': '\\\\'
  41.         },
  42.         rep;
  43.  
  44.  
  45.     function quote(string) {
  46.         escapable.lastIndex = 0;
  47.         return escapable.test(string) ?
  48.             '"' + string.replace(escapable, function (a) {
  49.                 var c = meta[a];
  50.                 return typeof c === 'string' ? c :
  51.                     '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  52.             }) + '"' :
  53.             '"' + string + '"';
  54.     }
  55.  
  56.  
  57.     function str(key, holder) {
  58.         var i,
  59.             k,
  60.             v,
  61.             length,
  62.             mind = gap,
  63.             partial,
  64.             value = holder[key];
  65.  
  66.         if (value && typeof value === 'object' &&
  67.                 typeof value.toJSON === 'function') {
  68.             value = value.toJSON(key);
  69.         }
  70.  
  71.         if (typeof rep === 'function') {
  72.             value = rep.call(holder, key, value);
  73.         }
  74.  
  75.         switch (typeof value) {
  76.         case 'string':
  77.             return quote(value);
  78.  
  79.         case 'number':
  80.  
  81.             return isFinite(value) ? String(value) : 'null';
  82.  
  83.         case 'boolean':
  84.         case 'null':
  85.  
  86.             return String(value);
  87.  
  88.         case 'object':
  89.  
  90.             if (!value) {
  91.                 return 'null';
  92.             }
  93.  
  94.             gap += indent;
  95.             partial = [];
  96.  
  97.             if (Object.prototype.toString.apply(value) === '[object Array]') {
  98.  
  99.                 length = value.length;
  100.                 for (i = 0; i < length; i += 1) {
  101.                     partial[i] = str(i, value) || 'null';
  102.                 }
  103.  
  104.                 v = partial.length === 0 ? '[]' :
  105.                     gap ? '[\n' + gap +
  106.                             partial.join(',\n' + gap) + '\n' +
  107.                                 mind + ']' :
  108.                           '[' + partial.join(',') + ']';
  109.                 gap = mind;
  110.                 return v;
  111.             }
  112.  
  113.             if (rep && typeof rep === 'object') {
  114.                 length = rep.length;
  115.                 for (i = 0; i < length; i += 1) {
  116.                     k = rep[i];
  117.                     if (typeof k === 'string') {
  118.                         v = str(k, value);
  119.                         if (v) {
  120.                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
  121.                         }
  122.                     }
  123.                 }
  124.             } else {
  125.  
  126.                 for (k in value) {
  127.                     if (Object.hasOwnProperty.call(value, k)) {
  128.                         v = str(k, value);
  129.                         if (v) {
  130.                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
  131.                         }
  132.                     }
  133.                 }
  134.             }
  135.  
  136.             v = partial.length === 0 ? '{}' :
  137.                 gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
  138.                         mind + '}' : '{' + partial.join(',') + '}';
  139.             gap = mind;
  140.             return v;
  141.         }
  142.     }
  143.  
  144.     if (typeof JSON.stringify !== 'function') {
  145.         JSON.stringify = function (value, replacer, space) {
  146.  
  147.             var i;
  148.             gap = '';
  149.             indent = '';
  150.  
  151.             if (typeof space === 'number') {
  152.                 for (i = 0; i < space; i += 1) {
  153.                     indent += ' ';
  154.                 }
  155.  
  156.             } else if (typeof space === 'string') {
  157.                 indent = space;
  158.             }
  159.  
  160.  
  161.             rep = replacer;
  162.             if (replacer && typeof replacer !== 'function' &&
  163.                     (typeof replacer !== 'object' ||
  164.                      typeof replacer.length !== 'number')) {
  165.                 throw new Error('JSON.stringify');
  166.             }
  167.  
  168.             return str('', {'': value});
  169.         };
  170.     }
  171.  
  172.     if (typeof JSON.parse !== 'function') {
  173.         JSON.parse = function (text, reviver) {
  174.  
  175.             var j;
  176.  
  177.             function walk(holder, key) {
  178.  
  179.                 var k, v, value = holder[key];
  180.                 if (value && typeof value === 'object') {
  181.                     for (k in value) {
  182.                         if (Object.hasOwnProperty.call(value, k)) {
  183.                             v = walk(value, k);
  184.                             if (v !== undefined) {
  185.                                 value[k] = v;
  186.                             } else {
  187.                                 delete value[k];
  188.                             }
  189.                         }
  190.                     }
  191.                 }
  192.                 return reviver.call(holder, key, value);
  193.             }
  194.  
  195.             cx.lastIndex = 0;
  196.             if (cx.test(text)) {
  197.                 text = text.replace(cx, function (a) {
  198.                     return '\\u' +
  199.                         ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  200.                 });
  201.             }
  202.  
  203.             if (/^[\],:{}\s]*$/.
  204. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
  205. replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
  206. replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  207.  
  208.                 j = eval('(' + text + ')');
  209.  
  210.  
  211.                 return typeof reviver === 'function' ?
  212.                     walk({'': j}, '') : j;
  213.             }
  214.  
  215.             throw new SyntaxError('JSON.parse');
  216.         };
  217.     }
  218. }());

Lo que hace el codigo es cargar una ruta que esta guardada en la base de datos y mostrarla en el ver.php

Espero me puedan ayudar!

Muchas gracias!
  #6 (permalink)  
Antiguo 27/08/2011, 13:10
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: SyntaxError: Unexpected token <

buenas,
si tienes una URL, creo que es más fácil de revisarlo. nótese que tienes código php, el cual no sabemos que exactamente hace.

__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #7 (permalink)  
Antiguo 27/08/2011, 13:57
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 9 meses
Puntos: 8
Respuesta: SyntaxError: Unexpected token <

[URL="http://200.60.247.182/rutas/"]Esta es la URL[/URL]
  #8 (permalink)  
Antiguo 27/08/2011, 14:14
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: SyntaxError: Unexpected token <

al cargar la página no me genera ningún error. tendrás que explicar como replicarlo. sin embargo, intente usando los botones y recibo otro tipo de error distinto. por ejemplo, en la linea #33 del mismo documento genera error porque estas intentando acceder a una propiedad de un objeto que no existe.

Código:
// directions no existe;
    var rleg = ren.directions.routes[0].legs[0];
te recomiendo que uses la consola de error del navegador para identificar los errores relacionados a referencias.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #9 (permalink)  
Antiguo 27/08/2011, 14:19
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 9 meses
Puntos: 8
Respuesta: SyntaxError: Unexpected token <

El error sale a la hora de guardar la ruta, cuando te manda a la siguiente pagina: [URL="http://200.60.247.182/rutas/ver.php"]ESTA[/URL]

Espero que me puedas ayudar, xq no entiendo la consola de error de chrome ni de firefox.

Muchas Gracias
  #10 (permalink)  
Antiguo 27/08/2011, 15:00
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: SyntaxError: Unexpected token <

parace que tu problema es que no le estas pasando los parámetros correctos a process.php. en este caso, process.php devuelve un mensaje de error tal que así, dependiendo que parámetros no ha recibido.
Código:
<br /> 
<b>Notice</b>:  Undefined index: mapdata in <b>C:\xampp\htdocs\rutas\process.php</b> on line <b>4</b><br /> 
<br /> 
<b>Notice</b>:  Undefined index: id in <b>C:\xampp\htdocs\rutas\process.php</b> on line <b>19</b><br />
por ende, en el callback de la misma función ($.post) se intenta analizar una respuesta con sintaxis no válida. fijate los parámetros que le estas pasando...
Código:
$.post("process.php",{command:'fetch', id:'$id'},function(data){
...
});
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #11 (permalink)  
Antiguo 27/08/2011, 15:16
Avatar de morfasto  
Fecha de Ingreso: julio-2011
Ubicación: Lima
Mensajes: 291
Antigüedad: 12 años, 9 meses
Puntos: 8
Respuesta: SyntaxError: Unexpected token <

Listo! ya lo corregi! MUCHISIMAS GRACIAS!.

Pero tengo otra duda, yo estoy usando XAMPP y me salia el error, pero cuando desintale xampp e instale appserver, no me salia el error, a que se debe eso?
  #12 (permalink)  
Antiguo 27/08/2011, 15:54
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: SyntaxError: Unexpected token <

debe ser configuración de php. en este caso, php estaba configurado para mostrar los errores en la salida.
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.

Etiquetas: ajax, token, unexpected
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 16:09.