我需要根据以下方案将数据库内容加载到变量data
。
var data = {
"62": {
sku: "62",
section: "bodyImage",
img: "images/diy-images/config-images/62.png",
label: "plain red",
price: "100"
},
"63": {
sku: "63",
section: "bodyImage",
img: "images/diy-images/config-images/63.png",
label: "plain pink",
price: "110"
},
"360": {
sku: "360",
section: "bodyImage",
img: "images/diy-images/config-images/360.png",
label: "plain gray",
price: "120"
},
};
我尝试使用以下功能实现这一目标,但它没有成功。我错过了什么?
var data = (function() {
$.ajax({
url: 'get_data.php',
data: "",
dataType: 'json',
success: function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var section = row[1];
var img = row[2];
var label = row[3];
var price = row[4];
}
}
});
});
答案 0 :(得分:1)
您可以通过'。'获取json对象值。操作
var data = (function() {
$.ajax({
url: 'get_data.php',
data: "",
dataType: 'json',
success: function(rows) {
for (var i in rows) {
var id = row.sku;
var section = row.section;
var img = row.img;
var label = row.label;
var price = row.price;
}
}
});
});
答案 1 :(得分:0)
您可以按名称处理属性:
for (var i in rows) {
var row = rows[i];
var id = row.sku; // or var id = i;
var section = row.section;
var img = row.img;
var label = row.label;
var price = row.price;
...
}
答案 2 :(得分:0)
var data = {}; // data variable for future use
$.ajax({
url: '',
data: '',
dataType: 'json',
success: function(rows) {
$.each(rows, function(i, val) {
var id = val.sku,
section = val.section,
img = val.img,
label = val.label,
price = val.price;
});
// if you want to update data variable then
data[sku] = {sku: sku, img: img, section: section, label: label, price: price};
// to set data to a content
$('#output_div').html(JSON.stringify(data));
}
})