[英]Retrieving and using a json associative array
I use jquery and ajax to retrieve a dynamically made array made in php, like so: 我使用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;
If I test the php file in browser, it outputs: 如果我在浏览器中测试php文件,则输出:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. 到现在为止还挺好。 But how do I use that array in jquery? 但是如何在jquery中使用该数组?
I have this jquery ajax: 我有这个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? 还是item_x也应该用引号引起来?
Now, how do I USE that array in jquery? 现在,如何在jquery中使用该数组?
If I try console.log(data[0]) it puts undefined 如果我尝试console.log(data [0]),它会置为未定义
Try to use $.each()
to iterate through that object, 尝试使用$.each()
遍历该对象,
$.each(data,function(key,val){
console.log(key,val);
});
If you want to access it without iterating it then simply use bracket notation
如果要访问它而不进行迭代,则只需使用方bracket notation
data['item_3'] //Simon
Or directly access it like, 或直接访问,
data.item_3 //Simon
Then convert it like an array as per your wish like this, 然后按照您的意愿像数组一样转换它,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly. 正如我在评论中提到的那样,php关联数组成为javascript对象,无法通过数字对其进行访问。
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: 在js中:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else: 在此示例中,EDIT关键字显然是一个令人误解的名称,最好将其命名为:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.