doupo5861 2014-07-03 03: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 03: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部