Error sending a JSON.stringify by means of an onclick event in javaScript

1

I want to send an associative array by means of a onclick event, when I send it when I capture it I get [object object] then try to send it of type string using JSON.stringify() I do it in the following way:

Event onclick

$('#div').html('<div class="col-xs-6 text-center"><a href="#" class="on-primary edit-row" onclick=\' mostrarDatos("'+JSON.stringify(datos)+'"); \'><i class="fa fa-pencil" aria-hidden="true"></i></a></div>');

This is shown when I capture the error in the console

mostrarDatos("[{"id":"1","nombre":"Prueba","direccion":"calle 2 av Siemprevivas","telefono":"123332123","observaciones":"Asdasdasdasdas","correo":"[email protected]","fechaInicio":"2016-07-01","fechaFin":"2017-02-08","logo":"archivos/mpg.jpg","costo":"9","estado":"1","Municipio_id":"1259","Estado_id":"777","Empresa_id":"2","municipio":"Cali"}]"); 

This is the error that shows me in the console

    
asked by Alan 12.08.2016 в 16:34
source

1 answer

1

The error is that you are putting double quotes inside a string delimited with double quotes, then that causes the string to break and give errors. You can see that it is wrong even in the coloration that StackOverflow gives to the code:

mostrarDatos("[{"id":"1","nombre":"Prueba","direccion":"calle 2 av Siemprevivas","telefono":"123332123","observaciones":"Asdasdasdasdas","correo":"[email protected]","fechaInicio":"2016-07-01","fechaFin":"2017-02-08","logo":"archivos/mpg.jpg","costo":"9","estado":"1","Municipio_id":"1259","Estado_id":"777","Empresa_id":"2","municipio":"Cali"}]"); 

A simple method would be to change the double quote from the outside to a simple one. Then everything will work well (and color well):

mostrarDatos('[{"id":"1","nombre":"Prueba","direccion":"calle 2 av Siemprevivas","telefono":"123332123","observaciones":"Asdasdasdasdas","correo":"[email protected]","fechaInicio":"2016-07-01","fechaFin":"2017-02-08","logo":"archivos/mpg.jpg","costo":"9","estado":"1","Municipio_id":"1259","Estado_id":"777","Empresa_id":"2","municipio":"Cali"}]'); 

But that would require changing the original string a lot. It is easier to escape the quotes from the result of cJSON.stringify in the following way:

JSON.stringify(datos).replace(/\"/g,"&quot;")

Here is a simplified example that works using this method:

function mostrarDatos(a) { alert(JSON.stringify(a))}

datos = [{"id":"1","nombre":"Prueba"}];
$('#div').html('<div class="col-xs-6 text-center"><a href="#" class="on-primary edit-row" onclick=\' mostrarDatos('+JSON.stringify(datos).replace(/\"/g,"&quot;")+'); \'><i class="fa fa-pencil" aria-hidden="true"></i>AAAA</a></div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="div">
</div>
    
answered by 12.08.2016 / 17:58
source