JSON解析中的链接问题

时间:2013-10-21 20:55:26

标签: jquery json

  

我目前正在使用API​​并需要访问每个故事的标题,图片和移动链接,我已经成功完成了标题和图片,但获取移动链接一直很困难。

.done(function( data ) {    
  var ol = $("<ol/>");

  $.each( data.headlines, function() {
    var h2 = $( "<h2/>" ).append(this.headline);

    ol.append(h2)

    $.each(this.images, function(){
      var img = $("<img>").attr("src", this.url); 
      ol.append(img)     
    });
  });
  $("body").append(ol);
});

查询API后检查响应正文显示移动链接的语法与标题和图像的语法不同。如何在不显示实际链接的情况下访问此链接并在浏览器中显示此链接?这就是响应主体的样子;

{
"timestamp": "2013-10-21T14:50:18Z",
"resultsOffset": 0,
"status": "success",
"resultsLimit": 10,
"resultsCount": 27,
"headlines": [{
    "headline": "Portugal land Sweden in playoff draw",
    "keywords": ["UEFA WCQ: Portugal land Sweden in playoff draw"],
    "lastModified": "2013-10-21T14:17:13Z",
    "audio": [],
    "premium": false,
    "mobileStory": "",
    "links": {
        "api": {
            "news": {
                "href": "http://api.espn.com/v1/sports/news/1588808?region=GB"
            }
        },
        "web": {
            "href": "http://espnfc.com/news/story/_/id/1588808/portugal-land-sweden-playoff-draw?ex_cid=espnapi_public"
        },
        "mobile": {
            "href": "http://m.espn.go.com/soccer/story?storyId=1588808&ex_cid=espnapi_public"
        }
    },
    "type": "Story",
    "related": [],
    "id": 1588808,
    "story": "",
    "title": "Portugal land Sweden in playoff draw",
    "linkText": "UEFA WCQ: Portugal land Sweden in playoff draw",
    "byline": "ESPN staff",
    "description": "European qualifying",
    "images": [{
        "height": 155,
        "alt": "World Cup qualifiers",
        "width": 275,
        "name": "Zlatan Ibrahimivoc Sweden Cristiano Ronaldo [275x155]",
        "caption": "One of either Zlatan Ibrahimovic or Cristiano Ronaldo will not be going to Brazil.",
        "type": "inline",
        "url": "http://espnfc.com/design05/images/2013/1021/zlatanibrahimivocswedencristianoronaldo_275x155.jpg"
    }],

2 个答案:

答案 0 :(得分:1)

这使您的h2成为网络版的链接:

.done(function(data){
    var ol = $("<ol/>");

    $.each( data.headlines, function() {
        var link = $("<a/>", {
            'href': this.links.web.href
        }).append(this.headline);

        var h2 = $( "<h2/>" ).append(link);

        ol.append(h2)

        $.each(this.images, function(){
            var img = $("<img>").attr("src", this.url); 
            ol.append(img)
        });
    });
    $("body").append(ol);
});

答案 1 :(得分:0)

我认为这应该有效:

.done(function (data) {
    var ol = $("<ol/>");

    $.each(data.headlines, function () {
        var h2 = $("<h2/>").append(this.headline);

        ol.append(h2);

        $('<a>Click to view article</a>', {
            href = this.links.mobile
        }).appendTo(ol);

        $.each(this.images, function () {
            var img = $("<img>").attr("src", this.url);
            ol.append(img)
        });
    });
    $("body").append(ol);
});