Wednesday 15 April 2015

javascript - Using data from one ajax request in another -



javascript - Using data from one ajax request in another -

i'm learning ruby going need js/jquery little project i'm working on friend. we're using last.fm api , trying build page we're going phone call 2 different url's json data.

http://ws.audioscrobbler.com/2.0/?method=user.getfriends&user=rj&api_key=3d7e6bb560deeb5d15af8176abf5c928&format=json

where can pull out friends username , info them, ,

http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=rj&period=7day&api_key=3d7e6bb560deeb5d15af8176abf5c928&format=json

where can top tracks each user.

the main problem i'm running in is, 1 time pull out username, need store variable , insert within '&user=rj&' on toptoptracks able pull each users top tracks.

$.ajax({ type : 'post', url : 'http://ws.audioscrobbler.com/2.0/?method=user.getfriends&user=rj&api_key=3d7e6bb560deeb5d15af8176abf5c928&format=json', datatype : 'json', success : function(data) { $('#success #f1').html(data.friends.user[0].name); $('#success #f2').html(data.friends.user[1].name); $('#success #f3').html(data.friends.user[2].name); }, error : function(code, message){ $('#error').html('error code: ' + code + ', error message: ' + message); } });

is have far (also 1 toptracks, reading on nesting them now), i'm not sure how user name , store variable utilize within top tracks (.each js?).

javascript can't threads other languages such java. round this, sets handlers - functions run later when triggered event. when phone call $.ajax({ ... });, javascript sets handler continues running. success handler won't run until later, after ajax response received. code placed after $.ajax({ ... }); run immediately. if want run after response received, have set within success handler. this:

success: function(data) { var users = data.friends.user; $.each(users, function(i, user) { $.ajax({ url: 'http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=' + user + '&period=7day&api_key=3d7e6bb560deeb5d15af8176abf5c928&format=json', ... success: function(data) { ... }, ... }); }); },

(note: way i've generated url bad. username containing & confuse server, giving malicious users much command on command sent. should uri-escape user.)

this works if have 1 handler each user. example, if each friend has section of page, can update each section results come in. if have function want run after all info has been received, gets little more tricky. in case should larn utilize library such async or q. although i'm not sure async available client-side javascript.

javascript jquery ajax json

No comments:

Post a Comment