pasar matriz asociativa de php a javascript [duplicado]

Posible duplicado:
How to pass an array of strings from PHP to Javascript using $.ajax()?

I want to pass a associative array from php code to javascript code. Please help me. how do I do this ? Is JSON helpful in this matter? If yes then please provide a simple code for help. Thank you.

Del comentario a continuación:
HTML + PHP code

    <input type="text" style="width:70;" name="<?php echo $quantity;?>" id="<?php echo $quantity;?>" onkeyup="check_valid_range('<?php echo $itemName;?>','<?php echo $quantity;?>',<?php echo json_encode($product_inventory);?>);">
<script type="text/javascript"> 
    function check_valid_range(product_field, quantity_field, inventory){ 
        var product = document.getElementById(product_field).value; 
        var quantity = document.getElementById(quantity_field).value; 
        var v = inventory[product]; 

preguntado el 27 de agosto de 11 a las 20:08

Done research much? This is actually a somewhat common task (however, converting to JSON is not technically enough, "</script>" appearing in the JSON is a counter-example. JSON "works" simply because it is a proper subset of Javascript Literal Notation. -

Why all the downvotes? This is not a terrible question. -

Think its because its a Duplicate. -

That a duplicate question exists is not a valid reason to downvote. You downvote because a question is difficult to understand or poorly-worded, not because someone else asked the same thing already. -

@cdhowie If you hover over the downvote button you will see that it says: "this question does not show any research effort". Given that there is almost 4k results in the linked search above and there is multiple duplicates, this clearly warrants a dv. There should be even more results on Google for that. This question does not deserve any upvotes. -

2 Respuestas

JSON is perfect:


$mySweetJSONString = json_encode($myAssocPHPArray);

    var iWantThePHPArrayHere = <?php echo $mySweetJSONString; ?>;

Usuario pst brought up these concerns:

  • "array("</script>") -- darn, just broke this "perfect" approach."
    It seems to work because (</script> => <\/script>):

  • "What about ]]> which could occur in XHTML?"
    The string is able to be transferred.


In regards to debugging the problem with the JS:
Are there any errors in the console? One of your document.getElementById(...) might be returning a null. Therefore the member value no existe

contestado el 23 de mayo de 17 a las 13:05

Thanks @cdhowie, I usually try to have complete code O_o - afuzzyllama

No problem, just trying to make the code clearer. :) +1 too, this is the right approach. - cdhowie

This is not very happy when "</script>" appears in the JSON. While JSON is a subset of JavaScript literals, not all JavaScript literals are valid in a <script> element (and I'm ignoring XHMTL entirely). I really wish there was a function designed just to facilitate this particular use-case with it's little caveats. - user166390

I am doing the same thing. json_encode function. But with a small difference, I am passing array of php to js by calling a function. And the function is not working. I just used alert() in the calling funcition to check if value is received. But nothing happened. - Abhimanyu1310

This is perfectly safe, even if the string contains </script>. PHP's json_encode escapes the / para este propósito. - Arnaud Le Blanc

I always believed JSON were invented for this:

    var myArray = <?=json_encode($myArray)?>;

This will render like this:

    var myArray = {"key":"value","key2":"value2",...};


This is perfectly safe for javascript, as JSON is a subset of the javascript syntax. This means that any JSON string can be treated as Javascript.

PHP json_encode() is perfectly safe when embedding JSON in <script> tags too, because PHP escapes the / personaje:

=> "<\/script>"

So it's not possible to write </script>, which is the only way to escape a <script> tag. (Everything in a <script> tag is part of the script, it's not parsed as HTML.) JSON allows to escape the / para este propósito.

So no JSON string can escape a <script> etiqueta.

Respondido 28 ago 11, 01:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.