利用并不总是存在的 JSON 属性。使用 jquery

Making use of a JSON attribute that doesn't always exist. Using jquery

我正在编写一个连接到 LastFM api 的简短脚本,以获取我最后一首被涂鸦的歌曲。我遇到的问题是 JSON 版本具有 "now playing" 的属性,当您当前正在收听歌曲时,该属性的值为 "true"。但是,如果没有歌曲播放,则该属性根本不存在。

这是我目前拥有的脚本,当我通过 spotify 或 iTunes 等收听歌曲时...它工作正常。

<p>
<p class="nowplaying"> <span class="track"></span> by <span class="artist"></span></p>
<p>
<script type="text/javascript">
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=JamesTaylor87&api_key=ADD-API-KEY-HERE&format=json', function(data) {

var artist = $(".artist"),
track = $(".track"),
np = $(".nowplaying"),
artistVal = data.recenttracks.track[0].artist["#text"],
trackVal = data.recenttracks.track[0].name,
nowplaying = data.recenttracks.track[0]["@attr"].nowplaying;

if(typeof nowplaying === "undefined"){
np.prepend("The last song I listened to was")
artist.append(artistVal);
track.append(trackVal);
} else {
np.prepend("I am currently listening to")
artist.append(artistVal);
track.append(trackVal);
}

});
</script>

然而,当我没有听任何东西时,我收到以下错误消息(在 safari 中)并且没有任何效果:

undefined is not an object (evaluating 'data.recenttracks.track[0]["@attr"].nowplaying')

在chrome中错误显示如下:

Uncaught TypeError: Cannot read property 'nowplaying' of undefined

我曾尝试在未定义时使用 if 语句,但没有用,我真的不知道还能尝试什么。任何帮助将不胜感激。

替换

data.recenttracks.track[0]["@attr"].nowplaying

data.recenttracks.track[0]["@attr"] && data.recenttracks.track[0 ["@attr"].nowplaying

如果 data.recenttracks.track[0]["@attr"] 未定义

,应该会停止错误的发生

尝试将您定义 nowplaying 的行更改为:

正在播放 = (data.recenttracks.track[0]["@attr"]) ? data.recenttracks.track[0]["@attr"].现在播放:未定义;

根据 chrome 错误,data.recenttracks.track[0]["@attr"] 未定义,这意味着您无法在其上查找 属性。您可以使用 if 语句或三元语句来检查它是否已定义,然后再检查其正在播放 属性.

var attrs = data.recenttracks.track[0]["@attr"];

if (typeof attrs !== 'undefined') {
   var nowPlaying = attrs.nowplaying;
}

试试这个:

var track = data.recenttracks.track[0];
var nowplaying = track.hasOwnProperty('@attr') && track['@attr'].nowplaying;

我刚刚用 Last.fm 为我的网站构建了一个非常相似的功能,运行 也遇到了同样的问题。我能够通过删除您包含的后续 .nowplaying 来解决问题。

见下文。希望对您有所帮助!

// get the api
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=YOURUSERNAME&limit=1&api_key=YOURAPIKEY&format=json', function(data) {

    var latesttrack = data.recenttracks.track[0]
    var trackTitle = latesttrack.name
    var trackArtist = latesttrack.artist["#text"]

    // detect if the track has attributes associated with it
    var nowplaying = latesttrack["@attr"]

    // if nowplaying is underfined
    if (typeof nowplaying === 'undefined') {

        $('.nowplaying').html("Currently listening to nothing.")

    } else {

        $('.nowplaying p').html("Currently listening to" + trackTitle + " by " + trackArtist)

    }

});

在此处查看实际效果:http://theadamparker.com/daily

    <script type="text/javascript">
        //<![CDATA[
            var lastfm_api     = 'http://ws.audioscrobbler.com/2.0/';
            var lastfm_methods = 'user.getRecentTracks';
            var lastfm_user    = 'YOUR_USERNAME';
            var lastfm_key     = 'YOUR_APIKEY';
            var lastfm_limit   = '1';

            var lastfm_json    = lastfm_api + '?method=' + lastfm_methods + '&user=' + lastfm_user + '&api_key=' + lastfm_key + '&limit=' + lastfm_limit + '&format=json';

            $.getJSON(lastfm_json, function(data) {
                var html = '';
                var song   = data.recenttracks.track[0].name, 
                    artist = data.recenttracks.track[0].artist["#text"], 
                    url    = data.recenttracks.track[0].url, 
                    cover  = data.recenttracks.track[0].image[0]['#text'];

                html += '<p><a href="' + url + '" title="Click here to view song in Last.fm" target="_blank">' + song + ' by ' + artist + '<br /><br /><img src="' + cover + '" style="display: block; width: 96px; height: 96px;" /></a></p><p><a href="https://twitter.com/intent/tweet?text=Listening%20♪%20' + song + '%20by%20' + artist + '%20via%20%40Lastfm&url=' + url + '&original_referer=' + url + '" title="Click here to view song in Last.fm" target="_blank">Share on Twitter</a></p>';

                $('#recent-tracks').append(html);
            });
        //]]>
    </script>

    <div id="recent-tracks"></div>