开发者

Get json object with jquery without using the $.each

开发者 https://www.devze.com 2023-03-29 08:44 出处:网络
I\'m using the recenttracks api from lastFm: www.last.fm/api/show?service=278 I\'m fetching the json format with jquery:
  • I'm using the recenttracks api from lastFm:

    www.last.fm/api/show?service=278

  • I'm fetching the json format with jquery:

    http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=melroymusic&api_key=690e1ed3bc00bc91804cd8f7fe5ed6d4&limit=5&format=json&callback=?

I want to retrieve the status of the first track

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

I have this cod开发者_运维知识库e 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");
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号