简体   繁体   中英

Get json object with jquery without using the $.each

I want to retrieve the status of the first track

"@attr":{"nowplaying":"true"}

I have this code to retrieve information about each track

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=melroymusic&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=3&format=json&callback=?",

function(data){
    $.each(data.recenttracks.track, function(i,item){
    $("#lastfmMenu").append("<div class='lastfmItem'><div class='lastfmText'>"+item.artist['#text']+"</div>" + "<div class='lastfmDate'>"+item.name+"</div></div>");
    });
});

to retrieve the nowplaying status of the first track, logically I would do

$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=melroymusic&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=3&format=json&callback=?",

function(data){
    if (data.recenttracks.track[0]['@attr'].nowplaying == true){
        $("#lastfmMenu").append("Now Playing");
    }
    else {
        $("#lastfmMenu").append("Just played");
    }
});

doesn't give me any results.

Hope you can help me out.

Is it because nowplaying is a string not a bool, so it should be

.nowplaying == "true"?

Not at a pc so I can't check.

did you try to parse it first? Try this (untested),

function(data){
  **var parsedData = $.parseJSON(data)**
    if (parsedData.recenttracks.track[0]['@attr'].nowplaying == true){
      $("#lastfmMenu").append("Now Playing");
    }
    else {
      $("#lastfmMenu").append("Just played");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM