2015-11-08 163 views
1

我有這個成功AJAX功能循環通過每個JSON響應返回「[對象對象]」

success: function(response){ 
    console.log(response); 
    if(response.success){ 
     $.each(response.vote, function(index, value){ 
      alert(value); 
     }); 
    } 
} 

,這從控制檯JSON響應(參考下面的圖像)

JSON response from the console

但它從警報提示中引發我「[Object Object]」,任何想法,線索,幫助,建議和建議?

+0

每一個'value'都是一個'object',alert會使它成爲一個字符串,這會在值上隱藏一個.toString,所以你得到'[Object Object]'。你可以嘗試'alert({})',這會給你相同的結果。如果你只是想看到這些鍵值對,你可以再次使用'json',alert(JSON.stringify(value))',但是如果你只想訪問它的值,可以使用'value.branch' ...等等。 – fuyushimoya

+0

所以任何想法如何在警報提示中呈現它像一個字符串?就像我要去顯示分支一樣,我得到每個分支。 –

+0

'alert'將對象轉換爲字符串,''GrandParent'Object'類中的'toString'方法使用原型鏈調用,因此它警告'[object Object]'。使用'console.log'。 – Tushar

回答

2

在你當前的代碼,該value是一個對象,但是,警報只能顯示string,所以它會使用.toString轉換您value爲一個字符串,然後成爲"[Object Object]"

要顯示value作爲鍵值對使用JSON.stringify(value),使之成爲json再次:

success: function(response){ 
    console.log(response); 
    if(response.success){ 
     $.each(response.vote, function(index, value){ 
      alert(JSON.stringify(value)); 
     }); 
    } 
} 

,如果你只是想訪問該值的屬性,用自己的鑰匙應該工作:

success: function(response){ 
    console.log(response); 
    if(response.success){ 
     $.each(response.vote, function(index, value){ 
      // This will alert each items' `bundle` value. 
      // It's enough in your case, but you may have to check if the target attribute you want to alert is also an object. 
      alert(value.bundle); 
     }); 
    } 
} 
3

請勿使用alert,而應使用console.log。您將能夠以這種方式查看所有對象並避免垃圾郵件。另外,如果您需要查看較深的對象,則可以使用類似https://github.com/WebReflection/circular-json的東西,這些對象甚至可以打印引用自身的對象(循環引用將無法打印大對象)。

+0

所以任何想法如何在警報提示中呈現它像一個字符串?就像我要去顯示分支一樣,我得到每個分支。 –

+0

@kishan寫道,你可以使用'alert(JSON.stringify(value))',但是如果對象有循環引用就會失敗,但只要試一下,對於簡單對象來說就完全沒問題。 – Vadorequest

3

alert使用對象的toString方法,它會返回這個[Object Object]的東西。如果你想很好地打印一個對象,你可以使用JSON.stringify(yourObject)

1

如果你想提醒不是使用警報(JSON.stringify(值))該值。