doupo5861 2014-07-03 11:01
浏览 85
已采纳

检索和使用json关联数组

I use jquery and ajax to retrieve a dynamically made array made in php, like so:

$json = array();

while ($row = $stmt->fetch_assoc()) {

    $json['item_'.$row['id']] = $row['name'];
}

header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;

If I test the php file in browser, it outputs:

{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}

So far so good. But how do I use that array in jquery?

I have this jquery ajax:

$.getJSON( "json.php", function(data) {
    console.log(data);
});

And testing that page in browser, it put this in console:

Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}

And that's ok right? Or should item_x also be in quotes?

Now, how do I USE that array in jquery?

If I try console.log(data[0]) it puts undefined

  • 写回答

2条回答 默认 最新

  • duanliu6083 2014-07-03 11:21
    关注

    As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.

    A solution would be to send an array of objects instead:

    while ($row = $stmt->fetch_assoc()) {
    
        $json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
    }
    

    the in js:

    data[0].key;
    data[0].value;
    

    EDIT obviously key is a misleading name in this example, better to call it something else:

    $json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
    //js
    data[0].id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题