我试图用JSON响应来填充数组。来自ajax的JSON响应是:
[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}]
我的代码如下:
var categories = [];
$('body').on("click", '.category_editable', function(){
$.ajax({
type:"get",
dataType: "json",
url:"ajax_php/get_all_categories.php",
success:function(data){
$.each( data, function( i, itemData ) {
categories[i] = itemData.category;
});
console.log(categories);
}
});
});
我得到的是没有钥匙的阵列,因为我不知道如何将它们推入阵列:
["Chloting", "Shoes", "Jewelry and Watches", "Accessories"]
但是我需要这样的对象格式:
["1":"Chloting", "2":"Shoes", "3":"Jewelry and Watches","4":"Accessories"]
答案 0 :(得分:1)
更改
var categories = [];
到
var categories = {};
答案 1 :(得分:0)
$(function(){
var d={};
var results=[
[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}]
];
$.each(results[0],function(k,v)
{
//alert(k+' '+v.id);
//alert(v.id+' '+v.category);
d[v.id]=v.category;
});
alert(JSON.stringify(d));
$("#output").html(JSON.stringify(d));
});
答案 2 :(得分:0)
var jsondata=[{"id":"1","category":"Chloting"},{"id":"2","category":"Shoes"},{"id":"3","category":"Jewelry and Watches"},{"id":"4","category":"Accessories"}];
var categories={};
$.each( jsondata, function( i, itemData ) {
categories[itemData.id] = itemData.category;
});
console.log(categories);