2017-03-08 20 views
-1

我想我可以做以下檢查數據值是否爲null,然後替換別的東西。檢查是否缺少JSON對象的項目

$.ajax({ 
    url: 'php/parsedjson.php', 
    dataType: 'json', 
    success: function(data) { 
     $.each(data, function(index, val) { 
      if (data[index].Manufacturers[0].Name != null){ 
      var manufacturer = data[index].Manufacturers[0].Name;} 
      else{ var manufacturer ="MISSING"} 
     }); 
    } 
}) 

然而,這會引發錯誤Uncaught TypeError: Cannot read property 'Name' of undefined當在JSON不被供應的數據值。

你如何檢查是否有值防止這種情況發生?

+2

檢查數據[index] .Manufacturers.length首先 –

+0

JSON是用於數據交換的*文本符號*。 [(More。)](http://stackoverflow.com/a/2904181/157247)如果你正在處理JavaScript源代碼,而不是處理*字符串*,那麼你不會處理JSON。 –

+0

@ T.J.Crowder不知道你的意思,從我的PHP返回的數據肯定是JSON格式。 – jonmrich

回答

1

應該很容易:

$.ajax({ 
    url: 'php/parsedjson.php', 
    dataType: 'json', 
    success: function(data) { 
     $.each(data, function(index, val) { 
      if (data[index].Manufacturers[0] && data[index].Manufacturers[0].Name){ 
      var manufacturer = data[index].Manufacturers[0].Name;} 
      else{ var manufacturer ="MISSING"} 
     }); 
    } 
}); 

你也來檢查數據[指數] .Manufacturers [0]前往名字之前,以避免空指針。

+0

完美!當我被允許時,我會接受答案。謝謝! – jonmrich