简体   繁体   中英

php associative array to javascript - doesn't work

I'm trying and trying. I think it has worked so far, but now it doesn't..

<?php
    $arr['123'] = 'QWE123';
    $arr['124'] = 'QWE124';
?>

<input id="arr" value=<?php echo json_encode($arr); ?> hidden>

<script>
    $(function (){
      var arrJS = $("#arr").val();
      console.log( arrJS );         // looks fine {"123":"QWEQWE123","124":"QWEQWE124"}
      console.log( arrJS['123'] );  // undefined !!!
    });
</script>

ps to object didn't help. arrJS = Object( $("#arr").val() );

You have to parse the json. You may do it like this:

var parsed = JSON.parse(arrJS);

Wish it helps!

it is just because json_encode convert array with double quotes "

when using double quotes " with value result will be

在此处输入图片说明

so change value="<?php echo json_encode($arr); ?>" to value='<?php echo json_encode($arr); ?>' value='<?php echo json_encode($arr); ?>'

 <?php
    $arr = [];
        $arr['123'] = 'QWE123';
        $arr['124'] = 'QWE124';
    ?>

    <input id="arr" value='<?php echo json_encode($arr); ?>' >

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
        $(function (){
          var arrJS = $("#arr").val();
          arrJS = JSON.parse(arrJS);
          console.log( arrJS );         
          console.log( arrJS['123'] );  
        });
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM