[AUXILIO] Insertar string JSON

Iniciado por Xargam, 26 Septiembre 2019, 04:06 AM

0 Miembros y 1 Visitante están viendo este tema.

Xargam

Este código me está enloqueciendo:

Código (javascript,26) [Seleccionar]
function mostrar(jsonStr : string) {
   console.log(typeof jsonStr );
   console.log(jsonStr);
   let jsonObj = JSON.parse(jsonStr );
   alert(`Id: ${jsonObj.Id} - Marca: ${jsonObj.Marca} -  Precio: ${jsonObj.Precio} -  Color: ${jsonObj.Color} - \
   Modelo: ${jsonObj.Modelo}.`);
}
function leer() {
   let tabla = "<table border='1'><thead><th>Id</th><th>Marca</th><th>Precio</th><th>Color</th><th>Modelo</th>\
   <th>Action</th></thead><tbody>";
   let xhttp = new XMLHttpRequest();
   xhttp.onreadystatechange = () => {
       if( xhttp.readyState == 4 && xhttp.status == 200) {
           let jsonObj = JSON.parse(xhttp.responseText);
           for(let i = 0 ; i < jsonObj.length ; i++) {
               let g  = JSON.stringify(jsonObj[i]);
               console.log(typeof g);
               console.log(g);
               tabla += "<tr>";
               tabla += `<td>${jsonObj[i].Id}</td>`;
               tabla += `<td>${jsonObj[i].Marca}</td>`;
               tabla += `<td>${jsonObj[i].Precio}</td>`;
               tabla += `<td>${jsonObj[i].Color}</td>`;
               tabla += `<td>${jsonObj[i].Modelo}</td>`;
               console.log(JSON.stringify(jsonObj[i]));
               tabla += "<td><input type='button' value='ver' onclick=\"mostrar(\'"+JSON.stringify +"\')\"</td>"; // AQUI
               tabla += "</tr>";
           }
           tabla += "</tbody></table>";
           (<HTMLDivElement>document.getElementById("result")).innerHTML += tabla;
       }
   }
   xhttp.open("GET", "./json_test.php", true);
   xhttp.send();
}


Donde esta el aquí no hay manera de que me reconozca las comillas que rodean al parametro de la funcion mostrar ( Que es un objeto json convertido a string). Probé de mil maneras y si consigo que funcione lo hace con comportamientos extraños. En la funcion mostrar en vez de recibir un string recibo un object. Evidentemente por la falta de las comillas que rodean el parametro. Ayuda por fa.

#!drvy

El problema que tienes seguramente es que stringify también imprime comillas y estas escapan a las comillas dobles de fuera. Una solución sería codificar el stringify y descodificarlo en la funcion mostrar

Código (javascript) [Seleccionar]
let attr_mostrar = encodeURIComponent(JSON.stringify(jsonObj[i]));
table += "<td><input type='button' value='ver' onclick=\"mostrar(\'"+attr_mostrar+"\')\"></td>";



Código (javascript) [Seleccionar]
function mostrar(jsonStr : string) {
   jsonStr = decodeURIComponent(jsonStr) || '';
   // ....



Saludos