dthp96899 2017-04-18 03:11
浏览 36

Php - 如何将数组编码为json并将其发送回去

Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost.

So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows:

$arrayResult = array();

        foreach ($result as $item) {
            array_push($arrayResult, array("type" => $item['type'],
                                           "count" => $item['count'])
            );

        }

        echo json_encode($arrayResult);

My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. As in, no data shown at all.

var arrayResult = null;

    $.get("../php/displayGraph.php",

        function (data) {

            arrayResult = (data);
            var result = JSON.parse(arrayResult);

            $("#results").html(arrayResult);
            //$("#results").html(JSON.parse(arrayResult));


        }
    );

The result of this is:

[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]

I am honestly at a loss in terms of what I even need to do to make it work. And here I thought java was bad with json.

  • 写回答

2条回答 默认 最新

  • drnycqxwz63508434 2017-04-18 03:30
    关注

    Try like this,

    $.get("../php/displayGraph.php",
    
        function (data) {
            $.each(data, function (i,item){
                console.log(item.type + " === " +item.count);
            } 
            /*arrayResult = (data);
            var result = JSON.parse(arrayResult);*/
    
            //$("#results").html(arrayResult);
            //$("#results").html(JSON.parse(arrayResult));
    
    
        }
    );
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭