Foros del Web » Programando para Internet » Javascript »

Problema con cadena de texto ultralarga

Estas en el tema de Problema con cadena de texto ultralarga en el foro de Javascript en Foros del Web. Hola. Tengo una variable en javascript que recibe una cadena de texto larguísima (mas de 40000 caracteres) con etiquetas html, que luego es impreso en ...
  #1 (permalink)  
Antiguo 16/05/2012, 15:38
 
Fecha de Ingreso: abril-2011
Ubicación: España, Mdrid
Mensajes: 89
Antigüedad: 13 años
Puntos: 1
Problema con cadena de texto ultralarga

Hola.
Tengo una variable en javascript que recibe una cadena de texto larguísima (mas de 40000 caracteres) con etiquetas html, que luego es impreso en un textarea RTF.
Con textos cortos funciona a la perfección pero me interesa muchísimo que se pueda con texto más largos. El script es el siguiente:

Código Javascript:
Ver original
  1. <script charset="ISO-8859-1">
  2. var command = "";
  3.  
  4. function InitToolbarButtons() {
  5.   var kids = document.getElementsByTagName('DIV');
  6.  
  7.   for (var i=0; i < kids.length; i++) {
  8.     if (kids[i].className == "imagebutton") {
  9.       kids[i].onmouseover = tbmouseover;
  10.       kids[i].onmouseout = tbmouseout;
  11.       kids[i].onmousedown = tbmousedown;
  12.       kids[i].onmouseup = tbmouseup;
  13.       kids[i].onclick = tbclick;
  14.     }
  15.   }
  16. }
  17.  
  18. function tbmousedown(e)
  19. {
  20.   var evt = e ? e : window.event;
  21.  
  22.   this.firstChild.style.left = 1;
  23.   this.firstChild.style.top = 1;
  24.   this.style.border="inset 1px";
  25.   if (evt.returnValue) {
  26.     evt.returnValue = false;
  27.   } else if (evt.preventDefault) {
  28.     evt.preventDefault( );
  29.   } else {
  30.     return false;
  31.   }
  32. }
  33.  
  34. function tbmouseup()
  35. {
  36.   this.firstChild.style.left = 1;
  37.   this.firstChild.style.top = 1;
  38.   this.style.border="outset 1px";
  39. }
  40.  
  41. function tbmouseout()
  42. {
  43.   this.style.border="solid 1px #a0c040";
  44. }
  45.  
  46. function tbmouseover()
  47. {
  48.   this.style.border="outset 1px";
  49. }
  50.  
  51.   function insertNodeAtSelection(win, insertNode)
  52.   {
  53.       // get current selection
  54.       var sel = win.getSelection();
  55.  
  56.       // get the first range of the selection
  57.       // (there's almost always only one range)
  58.       var range = sel.getRangeAt(0);
  59.  
  60.       // deselect everything
  61.       sel.removeAllRanges();
  62.  
  63.       // remove content of current selection from document
  64.       range.deleteContents();
  65.  
  66.       // get location of current selection
  67.       var container = range.startContainer;
  68.       var pos = range.startOffset;
  69.  
  70.       // make a new range for the new selection
  71.       range=document.createRange();
  72.  
  73.       if (container.nodeType==3 && insertNode.nodeType==3) {
  74.  
  75.         // if we insert text in a textnode, do optimized insertion
  76.         container.insertData(pos, insertNode.nodeValue);
  77.  
  78.         // put cursor after inserted text
  79.         range.setEnd(container, pos+insertNode.length);
  80.         range.setStart(container, pos+insertNode.length);
  81.  
  82.       } else {
  83.  
  84.  
  85.         var afterNode;
  86.         if (container.nodeType==3) {
  87.  
  88.           // when inserting into a textnode
  89.           // we create 2 new textnodes
  90.           // and put the insertNode in between
  91.  
  92.           var textNode = container;
  93.           container = textNode.parentNode;
  94.           var text = textNode.nodeValue;
  95.  
  96.           // text before the split
  97.           var textBefore = text.substr(0,pos);
  98.           // text after the split
  99.           var textAfter = text.substr(pos);
  100.  
  101.           var beforeNode = document.createTextNode(textBefore);
  102.           afterNode = document.createTextNode(textAfter);
  103.  
  104.           // insert the 3 new nodes before the old one
  105.           container.insertBefore(afterNode, textNode);
  106.           container.insertBefore(insertNode, afterNode);
  107.           container.insertBefore(beforeNode, insertNode);
  108.  
  109.           // remove the old node
  110.           container.removeChild(textNode);
  111.  
  112.         } else {
  113.  
  114.           // else simply insert the node
  115.           afterNode = container.childNodes[pos];
  116.           container.insertBefore(insertNode, afterNode);
  117.         }
  118.  
  119.         range.setEnd(afterNode, 0);
  120.         range.setStart(afterNode, 0);
  121.       }
  122.  
  123.       sel.addRange(range);
  124.   };
  125.  
  126. function getOffsetTop(elm) {
  127.  
  128.   var mOffsetTop = elm.offsetTop;
  129.   var mOffsetParent = elm.offsetParent;
  130.  
  131.   while(mOffsetParent){
  132.     mOffsetTop += mOffsetParent.offsetTop;
  133.     mOffsetParent = mOffsetParent.offsetParent;
  134.   }
  135.  
  136.   return mOffsetTop;
  137. }
  138.  
  139. function getOffsetLeft(elm) {
  140.  
  141.   var mOffsetLeft = elm.offsetLeft;
  142.   var mOffsetParent = elm.offsetParent;
  143.  
  144.   while(mOffsetParent){
  145.     mOffsetLeft += mOffsetParent.offsetLeft;
  146.     mOffsetParent = mOffsetParent.offsetParent;
  147.   }
  148.  
  149.   return mOffsetLeft;
  150. }
  151.  
  152. function tbclick()
  153. {
  154.   if ((this.id == "forecolor") || (this.id == "hilitecolor")) {
  155.     parent.command = this.id;
  156.     buttonElement = document.getElementById(this.id);
  157.     document.getElementById("colorpalette").style.left = getOffsetLeft(buttonElement);
  158.     document.getElementById("colorpalette").style.top = getOffsetTop(buttonElement) + buttonElement.offsetHeight;
  159.     document.getElementById("colorpalette").style.visibility="visible";
  160.   } else if (this.id == "createlink") {
  161.     var szURL = prompt("Introduce el enlace:", "http://");
  162.     if ((szURL != null) && (szURL != "")) {
  163.       document.getElementById('edit').contentWindow.document.execCommand("CreateLink",false,szURL);
  164.     }
  165.   } else if (this.id == "createimage") {
  166.     imagePath = prompt('Introduce la ruta de la imagen (de Internet) puedes subirla <a href="http://www.subirimagenes.com/">aquí</a>:', 'http://');
  167.     if ((imagePath != null) && (imagePath != "")) {
  168.       document.getElementById('edit').contentWindow.document.execCommand('InsertImage', false, imagePath);
  169.     }
  170.   } else if (this.id == "createtable") {
  171.     e = document.getElementById("edit");
  172.     rowstext = prompt("Introduce el número de filas: ");
  173.     colstext = prompt("Introduce el número de columnas: ");
  174.     rows = parseInt(rowstext);
  175.     cols = parseInt(colstext);
  176.     if ((rows > 0) && (cols > 0)) {
  177.       table = e.contentWindow.document.createElement("table");
  178.       table.setAttribute("border", "1");
  179.       table.setAttribute("cellpadding", "2");
  180.       table.setAttribute("cellspacing", "2");
  181.       tbody = e.contentWindow.document.createElement("tbody");
  182.       for (var i=0; i < rows; i++) {
  183.         tr =e.contentWindow.document.createElement("tr");
  184.         for (var j=0; j < cols; j++) {
  185.           td =e.contentWindow.document.createElement("td");
  186.           br =e.contentWindow.document.createElement("br");
  187.           td.appendChild(br);
  188.           tr.appendChild(td);
  189.         }
  190.         tbody.appendChild(tr);
  191.       }
  192.       table.appendChild(tbody);      
  193.       insertNodeAtSelection(e.contentWindow, table);
  194.     }
  195.   } else {
  196.     document.getElementById('edit').contentWindow.document.execCommand(this.id, false, null);
  197.   }
  198. }
  199.  
  200. function Select(selectname)
  201. {
  202.   var cursel = document.getElementById(selectname).selectedIndex;
  203.   /* First one is always a label */
  204.   if (cursel != 0) {
  205.     var selected = document.getElementById(selectname).options[cursel].value;
  206.     document.getElementById('edit').contentWindow.document.execCommand(selectname, false, selected);
  207.     document.getElementById(selectname).selectedIndex = 0;
  208.   }
  209.   document.getElementById("edit").contentWindow.focus();
  210. }
  211.  
  212. function dismisscolorpalette()
  213. {
  214.   document.getElementById("colorpalette").style.visibility="hidden";
  215. }
  216.  
  217. function Start() {
  218.   document.getElementById('edit').contentWindow.document.designMode = "on";
  219.  
  220.   //Aquí carga el texto
  221. <?php
  222.     if($autor == $_SESSION['nombre_usuario'].".html") {
  223.        
  224.     $contenido = file_get_contents($fichero);
  225.     echo "document.getElementById('edit').contentWindow.document.body.innerHTML = '".$contenido."';";
  226.    
  227.     }
  228.    
  229. ?>
  230.  
  231.   try {
  232.     document.getElementById('edit').contentWindow.document.execCommand("undo", false, null);
  233.   }  catch (e) {
  234.     alert("Tu navegador no es compatible.");
  235.   }
  236.  
  237.   InitToolbarButtons();
  238.   if (document.addEventListener) {
  239.     document.addEventListener("mousedown", dismisscolorpalette, true);
  240.     document.getElementById("edit").contentWindow.document.addEventListener("mousedown", dismisscolorpalette, true);
  241.     document.addEventListener("keypress", dismisscolorpalette, true);
  242.     document.getElementById("edit").contentWindow.document.addEventListener("keypress", dismisscolorpalette, true);
  243.   } else if (document.attachEvent) {
  244.     document.attachEvent("mousedown", dismisscolorpalette, true);
  245.     document.getElementById("edit").contentWindow.document.attachEvent("mousedown", dismisscolorpalette, true);
  246.     document.attachEvent("keypress", dismisscolorpalette, true);
  247.     document.getElementById("edit").contentWindow.document.attachEvent("keypress", dismisscolorpalette, true);
  248.   }
  249. }
  #2 (permalink)  
Antiguo 16/05/2012, 16:59
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Problema con cadena de texto ultralarga

en principio debería utilizar alguna herramienta para ver en que consiste el error.
De todas formas, file_get_contents(), te toma el texto como es, probá de aplicarle htmlentities() ó htmlspecialchars()

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #3 (permalink)  
Antiguo 17/05/2012, 09:51
 
Fecha de Ingreso: abril-2011
Ubicación: España, Mdrid
Mensajes: 89
Antigüedad: 13 años
Puntos: 1
Respuesta: Problema con cadena de texto ultralarga

En la consola de errores me salía este error: "unterminated string literal"
Buscando me he encontrado con esto que creo que ese es el problema ya que mete saltos de linea automáticos. Pero... ¿Cómo podría arreglarlo? Es decir ¿cómo podría automatizar ese proceso?
  #4 (permalink)  
Antiguo 17/05/2012, 10:08
Avatar de djaevi  
Fecha de Ingreso: marzo-2007
Ubicación: Moreno, Buenos Aires
Mensajes: 400
Antigüedad: 17 años, 1 mes
Puntos: 47
Respuesta: Problema con cadena de texto ultralarga

mas precisamente como esta formateado tu texto? si viene en parrafos digamos puedes suprimir los saltos de linea y agregar un \n (salto de linea javascript) para reemplazarlo
  #5 (permalink)  
Antiguo 17/05/2012, 12:35
Avatar de emprear
Colaborador
 
Fecha de Ingreso: junio-2007
Ubicación: me mudé
Mensajes: 8.388
Antigüedad: 16 años, 10 meses
Puntos: 1567
Respuesta: Problema con cadena de texto ultralarga

Pueden estar pasandote varias cosas, o que efectivamente tengas saltos de linea, o que tus textos tengan caracteres reservados, (comillas, comillas dobles etc),
ejemplo el archivo que cargas usa
este es un "texto",
ó
<p class='xxx'>Texto</p>

podés solucionarlo con cosas como esta
<?php
$contenido = file_get_contents('texto.txt');
$contenido= preg_replace("/(\n|\r)/","",$archivo);
$contenido = htmlentities($archivo);
?>
Aunque lo más fácil sería cargarlo con Ajax, que te codifica todo

Saludos
__________________
La voz de las antenas va, sustituyendo a Dios.
Cuando finalice la mutación, nueva edad media habrá
S.R.
  #6 (permalink)  
Antiguo 27/05/2012, 06:01
 
Fecha de Ingreso: abril-2011
Ubicación: España, Mdrid
Mensajes: 89
Antigüedad: 13 años
Puntos: 1
Respuesta: Problema con cadena de texto ultralarga

Cita:
Iniciado por emprear Ver Mensaje
Pueden estar pasandote varias cosas, o que efectivamente tengas saltos de linea, o que tus textos tengan caracteres reservados, (comillas, comillas dobles etc),
ejemplo el archivo que cargas usa
este es un "texto",
ó
<p class='xxx'>Texto</p>

podés solucionarlo con cosas como esta
<?php
$contenido = file_get_contents('texto.txt');
$contenido= preg_replace("/(\n|\r)/","",$archivo);
$contenido = htmlentities($archivo);
?>
Aunque lo más fácil sería cargarlo con Ajax, que te codifica todo

Saludos
Muchísimas gracias!!! Gracias a ti mi proyecto sigue adelante, este problema me había estancado. Gracias de nuevo.

Etiquetas: larga, cadenas
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 22:21.