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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀