Basically, I’m grabbing information from and API and outputing it in JS. Currently, I have things working in PHP. Instead of outputing JS with PHP, I would like to make it cacheable in a JS file. Using WordPress, I’ve grabbed the API information, json encoded it, and localized it for use in JS.
Here is my new JS var with the JSON string information:
var discographyJson = php_params.discography_setup.replace( /"/g, '"' );
This JSON output looks something like this:
{
"discography": [
{
"album_id":1,
"tracks":[
{"title":"Track 1 of Album 1"},
{"title":"Track 2 of Album 1"},
{"title":"Track 3 of Album 1"}
]
},
{
"album_id":2,
"tracks":[
{"title":"Track 1 of Album 2"},
{"title":"Track 2 of Album 2"},
{"title":"Track 3 of Album 2"}
]
}
]
}
What I would like to do, is loop through that content using JS/jQuery and create the following output, if possible.
$( '#album_1' ).click( function() {
myPlaylist.setPlaylist([
{ title: "Track 1 of Album 1" },
{ title: "Track 2 of Album 1" },
{ title: "Track 3 of Album 1" }
]);
});
$( '#album_2' ).click( function() {
myPlaylist.setPlaylist([
{ title: "Track 1 of Album 2" },
{ title: "Track 2 of Album 2" },
{ title: "Track 3 of Album 2" }
]);
});
Not being a JS/jQuery guru, I’ve racked my brain an spent many hours getting things this far. I cannot figure out how to loop through the JSON data to setup the jQuery functions. However, I’ve learned a bunch from the hours of trial and error debugging.
Assuming, that you already have parsed the JSON String into a real JSON-Object, I think this should be the way to go:
Note, that the album-variable is essential. If you don’t assign
eltoalbumhere, you would always use only the last element of the discography.