douyue7408 2013-12-14 04:37
浏览 64
已采纳

有效的JSON,但不能显示数组元素

I've been working on this for quite a while, and I've read TONS of posts on SO trying to figure out how I need to do this, and I can't seem to get it to work. I'm thinking it must be some aspect of the way I've coded things. So downvote away, but hopefully some kind soul will help me out.

I've tested using jsonlint, which comes back valid. I'm getting a response from the server with the values, I just can't seem to get anything in the browser other than when I just alert(response);. I need to be able to access the value of "cat_id_PK" and the other elements separately to loop through and display them in html table cells.

JSON:

{
"income": [
    {
        "cat_id_PK": 14,
        "cat_name": "test1",
        "cat_amount": "100.00"
    },
    {
        "cat_id_PK": 15,
        "cat_name": "test2",
        "cat_amount": "200.00"
    },
    {
        "cat_id_PK": 34,
        "cat_name": "test3",
        "cat_amount": "300.00"
    },
"expense": [
    {
        "cat_id_PK": 14,
        "cat_name": "tes41",
        "cat_amount": "400.00"
    },
    {
        "cat_id_PK": 15,
        "cat_name": "test5",
        "cat_amount": "500.00"
    },
    {
        "cat_id_PK": 34,
        "cat_name": "test6",
        "cat_amount": "600.00"
    }
]
}

PHP

    $array = array(
        'income'    => $income,
        'expense'   => $expense,
        'recurring' => $recurring
    );

    echo json_encode($array);

JQUERY

var request = $.ajax({
    type: "POST",
    url: 'inc/functions.php',
dataType: "JSON",
    data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
     //for each element put values in <td></td> tags.
});
  • 写回答

2条回答 默认 最新

  • dongmeijian1716 2013-12-14 05:08
    关注

    "I've tested using jsonlint, which comes back valid."

    No it doesn't, not for the JSON you've shown which has an error: it is missing a closing ] after the } and before the comma on the line before "expense" : .... But perhaps that's just a typo in your question given that you're generating the JSON with json_encode() (which wouldn't produce an error like that).

    " I just can't seem to get anything in the browser other than when I just alert(response);"

    So you are getting a value of some sort back then.

    " but if I just alert response[0], it will return just the first character of the JSON array."

    Yes, that's because response is a string - the raw string containing JSON, where what you want is to parse that string to get an object. Except that you don't have to do this manually because jQuery will do it automatically once you add dataType:"json" to your $.ajax() options.

    "I actually was missing the datatype on this one, but even after adding it in, no matter what I try, I'm getting [Object:Object] or undefined. I'm literally doing nothing more than alert(response);"

    Once you add the dataType:"json" the response parameter will be an object, which when you try to alert will correctly display as [object Object]. If you use console.log(response) then in your browser's console you'd see the actual object. You'd get undefined if you try to access a property that doesn't exist.

    "I need to be able to access the value of cat_id_PK and the other elements separately to loop through and display them in html table cells."

    Your response object has two properties, income and expenses, both of which are arrays of object. So use response.income to access the first array of objects, and response.expenses to access the second array of objects. The first income item is response.income[0] and the property you asked about is response.income[0].cat_id_PK. So you can use a for loop, or use $.each() to iterate over the array and do something with each .cat_id_PK property:

    var request = $.ajax({
        type: "POST",
        url: 'inc/functions.php',
        dataType: "json",
        data: {action: "display_categories", cur_month:cur_month}
    });
    request.done(function(response){
      //for each element put values in <td></td> tags.
      var tr = $("<tr></tr>");
      // using traditional for loop for income items
      for(var i = 0; i < response.income.length; i++) {
        $("<td></td>").text(response.income[i].cat_id_PK).appendTo(tr);
      }
      tr.appendTo("#idOfTableHere");
      var tr = $("<tr></tr>");
      // use equivalent jQuery $.each for expense items
      $.each(response.expenses, function(i, v) {
        $("<td></td>").text(v.cat_id_PK).appendTo(tr);
      });
      tr.appendTo("#idOfTableHere");
    });
    

    The code I've shown creates new td elements in each loop, appending them to new table rows, and then after each loop the new row is appended to a table that I've assumed already exists on your page with id="idOfTableHere".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)