Reputation: 509
Hi I am using json to send a list of songs to my table.The json response is coming fine till the controller url.But when I try to iterate through it and put the details in my table I am getting this error.
$(window).load(function(){
$.get("/MusicPlayer/getSongList", function(data){
var library = data;
listSongs(library);
});
});
function listSongs(library){
var table = $("#table");
var row;
$("#table tbody").remove();
library.forEach(function(song){ ***/*this is the line where there is error. */***
row = $("<tr></tr>");
$("<td />").addClass("song-select").append($("<input
/>").attr({type:"checkbox",class:"checkbox",value:song.title})).appendTo(row);
$("<td>"+song.title+"</td>").appendTo(row);
$("<td>"+song.album+"</td>").appendTo(row);
$("<td>"+song.artist+"</td>").appendTo(row);
$("<td>"+song.rating+"</td>").appendTo(row);
$("<td>"+song.composer+"</td>").appendTo(row);
$("<td>"+song.genre+"</td>").appendTo(row);
row.click(viewFunction());
row.appendTo(table);
});
[
{
"title": "15 - Jacob's Theme.mp3",
"album": "The Twilight Saga - Eclipse",
"artist": "Howard Shore",
"rating": "2",
"composer": "carter ruwell",
"genre": "Soundtrack"
},
{
"title": "07_-_Vennante.mp3",
"album": "Andala Rakshasi (2012)",
"artist": "Ranjith",
"rating": "0",
"composer": "Rathan",
"genre": "TeluguMusic"
},
{
"title": "08. One Simple Idea.mp3",
"album": "Inception (OST)",
"artist": "Hans Zimmer",
"rating": "0",
"composer": "null",
"genre": "?????????"
}
]
Upvotes: 1
Views: 1922
Reputation: 114579
A json
response is a string in a very specific format, but still just a string.
Before being able to use it as Javascript data you need to parse it using JSON.parse
.
Upvotes: 1
Reputation: 5391
json object does not have forEach
function defined for it.
use for loop :
for(var song in library) {
console.log(song, result[song]);
}
or with jquery each
:
$.each(library, function(key, value) {
});
forEach
is just for simple arrays and in the environment that supports ECMAScript5
.
take a look at this too : For-each over an array in JavaScript?
Upvotes: 0
Reputation: 13858
I guess you need to $.parseJSON
, since library
should be a JSON formatted string, not really an array.
$.parseJSON(library).forEach(function(song){ .....
Upvotes: 2