2016-10-15 40 views
-2

JSONでオブジェクトをプッシュできませんが、console.log()は機能します。 console.log()はオブジェクトの追加を示しますが、jsonの文字列は表示されません。 [0] .comments JSONでオブジェクトをプッシュできませんが、console.log()は動作します

var results = [{ 
 
    "id": 0, 
 
    "name": "Green", 
 
    "category": "project", 
 
    "year": 2008, 
 
    "description": "my description", 
 
    "comments": [{ 
 
    "rating": 5, 
 
    "comment": "Perfect", 
 
    "author": "Sandra", 
 
    "date": "2012-10-16T17:57:28.556094Z" 
 
    }, { 
 
    "rating": 4, 
 
    "comment": "Cool", 
 
    "author": "Milena", 
 
    "date": "2014-09-05T17:57:28.556094Z" 
 
    }, { 
 
    "rating": 3, 
 
    "comment": "No bad", 
 
    "author": "Milan", 
 
    "date": "2015-02-13T17:57:28.556094Z" 
 
    }, { 
 
    "rating": 4, 
 
    "comment": "Good job", 
 
    "author": "Toma", 
 
    "date": "2013-12-02T17:57:28.556094Z" 
 
    }, { 
 
    "rating": 2, 
 
    "comment": "OK", 
 
    "author": "Aleksandar", 
 
    "date": "2011-12-02T17:57:28.556094Z" 
 
    }] 
 
}]; 
 

 
document.getElementById('show').innerHTML = results[0].comments[1].author; 
 

 
document.getElementById("sendComment").onclick = function() { 
 

 
    var hg = { 
 
    "rating": 1, 
 
    "comment": "Hello", 
 
    "author": "X", 
 
    "date": "2014-09" 
 
    } 
 
    results[0].comments.push(hg); 
 
    console.log(results[0].comments); 
 
}
<div id='show'></div> 
 
<button id='sendComment'>Send</button>

+1

第1に、JSONはオブジェクトだけです。第2に、コンソールで見ると、意図したとおりに動作し、ファイルを更新せず、ソースに表示されません。 – adeneo

+1

うまく働いています。だからうまくいかない。 JSONを更新すると、JSONファイルは更新されません。それはちょうどメモリ内で更新されます.... – epascarello

+0

ここで試してみてくださいリフレッシュ後、すべて同じ – Aleksandar

答えて

0

結果は、オブジェクトの配列ではなく、JSON文字列です。すべて正常に動作します。新しいオブジェクトが配列に追加されます。

+0

新しいオブジェクトはここに永続的に残らない – Aleksandar

+0

なぜですか?次回にボタンをクリックすると、別の同じオブジェクトが追加されていることがわかります。 –

+1

ページリフレッシュ後にクライアント上のデータを保持するには、JSON.stringify(results [0] .comments)やlocalstorage –

関連する問題