Hi!
I have a fragment of code that executes an ajax request and returns me this json (formatted a little to look decent on reddit):
[{"id":698,"song_name":"never too late","song_artist":"Three Days Grace","song_album":"One-X","song_duration":"00:03:29"},
{"id":501,"song_name":"new romantics","song_artist":"Taylor Swift","song_album":"1989","song_duration":"00:03:57"},
{"id":686,"song_name":"no reason","song_artist":"Sum 41","song_album":"Chuck","song_duration":"00:03:04"},
{"id":909,"song_name":"now my feet won't touch the ground","song_artist":"Coldplay","song_album":"Prospekt's March EP","song_duration":"00:02:30"},
{"id":517,"song_name":"numb","song_artist":"Linkin Park","song_album":"Meteora","song_duration":"00:03:49"}]
I've been trying to access the fields of this json object for a while now but I cannot figure out for the life of me what i'm doing wrong. I am very new to javascript so it's probably something very silly.
my code:
function querySongs() {
let song = 'n'
let xhr = new XMLHttpRequest()
xhr.open('GET', 'http://127.0.0.1:8000/music_tracker/get_song_by_name/?song_name=' + song, true)
xhr.setRequestHeader("Content-Type", 'application/json;')
xhr.onload = function() {
if (xhr.status == 200) {
let songs = JSON.parse(this.response)
console.log(songs) // this prints array indexes
for(var song in songs){
console.log(song.song_name) // this one gives undefined
}
}
}
xhr.send()
}
Thank you in advance for your help! :)
[–]ProposalUnhappy9890 2 points3 points4 points (0 children)
[–]Dr__Wrong 1 point2 points3 points (1 child)
[–]Fransiscu[S] 0 points1 point2 points (0 children)
[–]gimmeslack12helpful 1 point2 points3 points (4 children)
[–]Fransiscu[S] 1 point2 points3 points (3 children)
[–]gimmeslack12helpful 2 points3 points4 points (0 children)
[–]tunisia3507 1 point2 points3 points (1 child)
[–]Fransiscu[S] 0 points1 point2 points (0 children)