2

我需要根据以下方案将数据库内容加载到变量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];
            }
        }
    });
});​
4

3 回答 3

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;

            }
        }
    });

});​
于 2012-06-02T11:16:54.463 回答
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;
    ...
}
于 2012-06-02T10:59:55.643 回答
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));
 }
})
于 2012-06-02T11:01:27.703 回答