Obtain values of a jsp variable in javascript

1

I was trying 2 ways to get values in a variable jsp in my javascript, but they give me different results

FIRST ALTERNATIVE

//Con esto obtengo un string con este valor "[1,2,3,4]"
<%
String permisos= (String)session.getAttribute("permisos");
%>

//Ahora ess valor lo paso aqui 
<input id="permisos" type="hidden" value="<%=permisos%>">

//En el script hago que se escriba su valor
var cadena = $('#permisos').val();
alert(cadena);
//El script me vota el siguiente valor [1,2,3,4]

SECOND ALTERNATIVE

//Con esto obtengo un string con este valor "[1,2,3,4]"
<%
String permisos= (String)session.getAttribute("permisos");
%>
//Ahora el valor  lo pongo directamente en el script a diferencia del primer caso
var cadena = <%=permisos%>
alert(cadena);
////Con esto obtengo un string con este valor "1,2,3,4"
  • Why the difference in what they return?
  • The most important thing is that using the first method I can use the js externally and call it to other pages, but it returns [1,2,3,4] (what does not work for me), and using the second form it returns 1,2,3,4 (what I need), BUT I would not allow it to be called js because it has a variable jsp inside.
  • asked by angelo1793 10.09.2018 в 19:01
    source

    1 answer

    1

    It's simple, in Javascript what is done is the following

    var cadena = [1,2,3,4]
    

    With the form above, the following is done

    var cadena = '[1,2,3,4]', 
    

    so your second string is not a string but an array of integers. You can fix it with

    var cadena = JSON.parse($('#permisos').val());
    
        
    answered by 11.09.2018 в 03:36