2012-10-07 44 views
3

使用以下JavaScript即時通訊。它寫得很好,直到得到一個沒有價值的結果。在控制檯登錄它顯示了這個JavaScript檢查是否null從json

Uncaught TypeError: Cannot read property 'text' of null

,但低於我的劇本似乎並沒有工作

  var checkCaption = photo.caption.text; 
      if (checkCaption == null) { 
       caption = 'meh'; 
      } else { 
       caption = photo.caption.text; 
      } 

回答

8

在你的榜樣,photo.caption爲空,所以在photo.caption.text調用代碼休息,檢查完成之前。

var caption; 

if(photo.caption != null) { // Covers 'undefined' as well 
    caption = photo.caption.text; 
} else { 
    caption = "meh"; 
} 
+0

未捕獲TypeError:無法使用'in'運算符來搜索空' – ngplayground

+0

'中的文本我的不好,我修復了它 –

0

讀取錯誤:誰說不能讀取屬性「文本」空的

這意味着photo.caption爲空

1

在我來說,我使用JSON.stringify來檢查我收到了REST服務器{}(空)響應:

if (JSON.stringify(response.data)=='{}') { 
     //the response is null 
} 
else { 
     //the response of JSON is not null 
} 

它工作正常,我來檢查響應無論是否爲空。