gpt4 book ai didi

javascript - 检索和使用 json 关联数组

转载 作者:行者123 更新时间:2023-12-02 17:14:30 24 4
gpt4 key购买 nike

我使用 jquery 和 ajax 来检索在 php 中动态创建的数组,如下所示:

$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;

如果我在浏览器中测试 php 文件,它会输出:

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

到目前为止一切顺利。但是我如何在 jquery 中使用该数组呢?

我有这个jquery ajax:

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

并在浏览器中测试该页面,它将其放入控制台:

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

这样可以吗?或者 item_x 也应该用引号引起来吗?

现在,我如何在 jquery 中使用该数组?

如果我尝试 console.log(data[0]) 它会显示未定义

最佳答案

正如我在评论中提到的,php 关联数组变成了 javascript 对象,无法通过数字方式访问。

解决方案是发送对象数组:

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

$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}

js中的:

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

编辑显然 key 在此示例中是一个误导性的名称,最好将其称为其他名称:

$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;

关于javascript - 检索和使用 json 关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24551959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com