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 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存