正确的ajax调用JSON数据

时间:2015-03-18 20:57:04

标签: jquery ajax json

第一次尝试从JSON文件中检索数据时,老老实实地不知道如何获取我想要的对象。

有人可以告诉我如何获取Family NamefamilyAttributes等值?我根本不知道如何处理数据。

当前的AJAX通话

$.ajax({
    type: 'GET',
    url: 'https://somesite.com/EloMS.json',
    data: { category : 'Touchmonitors' },
    dataType: 'json',
    success: function(data) {
        $.each(data, function(index, element) {
            console.log(element);
        });
    }
});

JSON语法:

{
  "products": [
    {
      "Family Name": "3201L",
      "Type": "IDS",
      "Size (inches)": 32,
      "Aspect Ratio": "16:9",
      "Part Number": "E415988",
      "Product Description": "ET3201L-8UWA-0-MT-GY-G",
      "Marketing Description": "3201L 32-inch wide LCD  Monitor, VGA, HDMI & DisplayPort video interface, 01 series enhanced AV, IntelliTouch Plus USB touch controller interface, Worldwide-version, Clear, Gray ",
      "Advance Unit Replacement": "",
      "Elo Elite": "",
      "Package Quantity": 1,
      "Minimum Order Quantity": 1,
      "List Price": 1800
    },
    { ... }
  ]
  "families": [
    {
      "category": "Touchmonitors",
      "types": [
        "Desktop",
        "Display",
        "Open Frame"
      ],
      "image": "",
      "familyAttributes": [
         {
          "type": "Display",
          "image": "",
          "families": [
            {
              "familyName": "0700L",
              "image": ""
            }
          ]
        },
        { ... }
     }
  ]
}

我尝试了element.category的几种变体,但除了完整的对象之外,还无法获得任何数据。

2 个答案:

答案 0 :(得分:1)

对于product对象,您需要:

data.products[n]["Family Name"]

其中nproducts数组的整数偏移量。

对于familyAttributes,您需要:

data.families[n].familyAttributes

由于密钥中的空格字符,第一种情况下需要["string"]语法。

答案 1 :(得分:-1)

你可以使用getJSON(),文档在这里: http://api.jquery.com/jquery.getjson/

您可以像这样访问您的模型:

$.getJSON('https://somesite.com/EloMS.json', function(data) {
    // Products table
    var products = data.products;
    // Product type
    var typeProduct = data.products[0].Type;
    // familyAttributes
    var familyAttributes = data.families[0].familyAttributes;
    // Family Name
    var familyName = data.products[0]['Family Name'];
});
相关问题