2015-03-18 106 views
0

第一次嘗試從JSON文件中檢索數據,並且誠實地不知道如何獲取我想要獲取的對象。正確調用JSON數據的ajax

有人可以告訴我如何獲取值如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幾個變化,但一直沒能得到比全之外的任何數據對象。

回答

1

對於product對象,你會想:

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

其中n是整數偏移到products數組中。

familyAttributes,你需要:

data.families[n].familyAttributes 

["string"]語法是因爲關鍵中的空格字符在第一種情況下必要的。

+0

您是否發現刪除密鑰中的空格有什麼好處?另外 - 我不確定什麼'index'和'element'在'$ .each()'調用中,只是遵循我找到的一個例子。 – Adjit 2015-03-18 21:08:55

+0

刪除空格將允許在代碼中使用更簡潔的語法。外部'data'對象上的'.each'在這裏用處不大,因爲您知道這兩個對象被稱爲'products'和'families'。實際上,當傳遞一個Object時,兩個參數實際上應該是'key'和'value' - 'index'和'element'是您在jQuery集合中調用'$ .each'時得到的。 – Alnitak 2015-03-18 21:11:31

+0

有沒有指向'data:{category:「Touchmonitors」}它似乎沒有做任何事情......我想嘗試做的只是獲取JSON文件的某些部分,具體取決於我何時需要它們 – Adjit 2015-03-18 21:14:38

-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']; 
}); 
+0

我知道,但這真的沒有幫助我... – Adjit 2015-03-18 20:59:28