dqdpz60048 2017-01-27 08:24
浏览 55

PHP:如何在Javascript中将json解码为数组形式?

I've an array in my php called as $tempoHeader, for example:

Example Array $tempoHeader

-------
Array
(
   [0] => red
   [1] => green
   [2] => yellow
   [3] => blue
)

I want to send it into my external javascript, so I do this one in my php code:

My PHP: header.php

$tempoHeader = array_diff_assoc($modelData, $data);
<script type="text/javascript">var header = <?php echo json_encode($tempoHeader); ?>;</script>
<script type="text/javascript" src="upload_header.js"></script>

In my javascript, I've try to console.log(header); and I got this in my console

Array [ "red", "green", "yellow", "blue" ]

My JS: upload_header.js

$(window).load(function() {
console.log(header);                    //this work and print out the header json
   var myObject = JSON.parse(header);
   var myArray = jQuery.parseJSON(header);
   console.log(myArray);                   //didn't print out anything
   console.log(myObject);                  //didn't print out anything
});

How do I can decode this json back as $tempoHeader array form?

Note: I've read this issue jQuery JSON Decode ( PHP to Javascript), and I've try the suggestion such as jQuery.parseJSON(header);, JSON.parse(header); but I got nothing

  • 写回答

3条回答 默认 最新

  • dongzichan2886 2017-01-27 08:26
    关注
    $res = json_decode( $tempoHeader, true );
    echo $res->array_name[index];
    

    I hope this help

    评论

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决