I'm new to jQuery and JavaScript, so please bear with me. I am trying to perform an AJAX get request to retrieve my JSON file which contains track information is formatted like this:
[
{
"name" : "Short Skirt, Long Jacket",
"artist" : "Cake",
"album" : "Comfort Eagle",
"genre" : "Rock",
"year" : 2001,
"albumCoverURL" : "images/ComfortEagle.jpg",
"bandWebsiteURL" : "http://www.cakemusic.com"
},
{
...
}
]
I am trying doing this with these two functions:
function loadJSON ()
{
$.getJSON("lab4.json", updateHTML(result));
}
$(document).ready(function ()
{
$("site").click(function ()
{
loadJSON();
});
});
When the user clicks on the link with the id "site" I want to sent an asynchronous javascript call to retrieve my JSON file. Upon success it should call my updateHTML function here:
function updateHTML (result)
{
var templateNode = document.getElementById("song-template").cloneNode(true);
document.removeChild(getElementById("song-template"));
$.each(result, function(i, song)
{
var songNode = templateNode.cloneNode(true);
});
}
Now, here's where I'm stuck: Now that I have this cloned node, how do I use jQuery to fill out all of the fields in the HTML here:
<a id="site" href="#"><img id="coverart" src="noalbum.png" /></a>
<h1 id="title"></h1>
<h2 id="artist"></h2>
<h2 id="album"></h2>
<p id="date"></p>
<ul id="genres"></ul>
Normally, I would just go like:
$("site").attr("src","images/ComfortEagle.jpg");
But now I'm faced with two issues. One, how do I get the new url from my JSON object that I have read in as 'song', and two, how do I target the "site" id inside the node that I cloned before I add it back to the document's html? Thanks!
You can concatenate the ID from your keys
$.each(dataObj, function(key, val) {
//dataObj is your returned JSON
if ($("#" + key).length)
$("#" + key).val(val);
});
first, If you're going to use jquery, use jquery.
You can use th ejquery clone() method rather than the js cloneNode to accomplish this.
I think this is what your trying to do to with a more jquery ish solution.
var song = [1,2,3,4];
var templateNode = $("#lala");
$.each(song, function(key, val){
var songNode = templateNode.clone(true);
songNode.children('span.yo').text(val);
$('#wrap').append(songNode);
});
AS for the json parsing, on each iteration, you should be able to access the props like any other json, so in the each loop, just target a prop like:
song.albumCoverURL