显示JSON对象不起作用

时间:2013-07-16 00:56:49

标签: javascript ajax jquery jsonp

我有一个JSONP,我希望在列表中显示,我设法在列表中显示文件中的艺术家名称。但现在我想显示第三个JSONP对象,但我似乎可以获取它。我该怎么做?

我想显示JSONP中的"links": { "artists.albums": { href: "...", ...}

JSONP文件位于:http://pcampbellem-test.nodejitsu.com/api/v1/artists.json?callback=MyCallback

JSONP(取自上面的网址以便于阅读):

MyCallBack({
    "artists": [
        {"id":"1","name":"Radiohead","website":"http://radiohead.com/","href":"/api/v1/artists/1.json"},
        {"id":"2","name":"Nick Cave & The Bad Seeds","website":"http://www.nickcave.com/","href":"/api/v1/artists/2.json"},
        {"id":"3","name":"John Frusciante","website":"http://johnfrusciante.com/","href":"/api/v1/artists/3.json"}
    ],

    "meta": {
        "artists": {
            "page": 1,
            "page_size": 10,
            "count": 3,
            "includes": [],
            "page_count": 1,
            "previous_page": null,
            "next_page": null,
            "previous_href": null,
            "next_href": null
        }
    },

    "links": {
        "artists.albums": {
            "href": "/api/v1/albums.json?artist_id={artists.id}", // I just wanna fetch this bit and display it in a list
            "type": "albums"
        }
    }
});

JS:

(function($, window) {

  var jsonUrl = 'http://pcampbellem-test.nodejitsu.com/api/v1/artists.json?callback=MyCallback'

  $.ajax({
      type: 'GET',
      url: jsonUrl,
      async: false,
      jsonpCallback: 'MyCallback',
      contentType: "application/json",
      dataType: 'jsonp',
      success: function(data) {

          $.each(data, function(key, val) {

              if (key === 'artists') {

                  for(var i = 0, max = val.length; i < max; i++) {
                      $('#artists-list').find('ul').append('<li><a href="' + val[i].website + '" class="edit">' + val[i].name + '</a></li>');
                  }
              }

              console.log(val.links); // this throws an error...
          });

      },

      error: function(err) {
          console.log(err.message);
      }
  });

}(jQuery, window));

1 个答案:

答案 0 :(得分:2)

success: function(data) {
    var albums_href = data.links['artists.albums'].href;
    // Do something with albums_href
    // Display list of artists
    $.each(data.artists, function(i, artist) {
        $('#artists-list ul').append('<li><a href="' + artist.website + '" class="edit">' + artist.name + '</a></li>');
    });
}

您必须对artists.albums使用数组表示法,因为属性名称包含标识符中不允许的字符。