Created
February 19, 2012 22:32
-
-
Save phette23/1866234 to your computer and use it in GitHub Desktop.
Last.fm Recent Tracks API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h3>Last.fm Scrobbles</h3> | |
<!-- div below will be filled in with formatted contents of API response --> | |
<div id="recent-tracks" style="display:none;"><a href="http://last.fm/">Last.fm</a> data hasn't loaded yet.</div> | |
<!-- leave as display:none for the fade in effect --> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ //put everything in a wrapper to ensure jQuery's use of $ doesn't conflict with other libraries | |
//see http://www.last.fm/api/show/user.getRecentTracks for API documentation | |
//there are more optional parameters such as to, from, & page that this example doesn't use | |
var user = "username" | |
var apiKey = "your API key" | |
//using jQuery's GET method for ajax | |
$.get("http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=5&user=" + user + "&api_key=" + apiKey, | |
function(response){ //callback function, runs upon receiving response | |
var output = '<ul style="list-style-type:none">'; | |
$(response).find('track').each(function(){ | |
var trackURL = $(this).find('url').text(); //url for the specific track | |
var trackName = $(this).find('name').text(); //name of the track | |
var artist = $(this).find('artist').text(); //artist | |
var date = $(this).find('date').text(); //date & time played | |
var trackFinal = "<li>"; | |
if (date) { | |
trackFinal += date + " - "; | |
} | |
else { | |
trackFinal += "Now playing: "; //currently-playing songs have no date | |
}; | |
trackFinal += " <a href='" + trackURL + "'>" + trackName + "<\/a> by <a href='http://www.last.fm/music/"; | |
trackFinal += encodeURIComponent(artist) //artist names may have special characters e.g. Why? | |
trackFinal += "'>" + artist + "<\/a><\/li>"; | |
output += trackFinal; | |
}); | |
output += "</ul>"; | |
$('#recent-tracks').html(output).fadeIn('slow'); //nice fade in effect | |
}, | |
"xml"); //expecting XML as a response, could leave this blank | |
}(jQuery)); //execute wrapper function with $ = jQuery |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment