如何从JSON结果数组中设置变量

时间:2014-11-15 17:59:59

标签: jquery ajax json

我从摘要API中获取JSON数据,并且我想使用其中一个返回值作为我稍后可以操作的变量。我从此网址获取JSON数据:

http://clipped.me/algorithm/clippedapi.php?url=http://www.bbc.com/news/world-asia-china-30067035

然后返回:

{"title":"BBC News - Hong Kong protest leaders denied Beijing flight","summary":["They had hoped to meet China's leaders as part of their push for greater democracy, but were told at the airport that their travel permits were invalid.","They want Beijing to allow more candidates to stand in the territory's next leadership election in 2017.","The group were greeted at the airport by fellow democracy activists, who unfurled yellow umbrellas - a symbol of Hong Kong's democracy movement."],"source":"bbc.com"}

我已经尝试了var story = json.results[0].summary;,但它无效。

我的代码如下所示:

$.ajax({
     type : "GET",
     crossOrigin: true,
     dataType : "jsonp",
     url : "http://clipped.me/algorithm/clippedapi.php?url=http://www.bbc.com/news/world-asia-china-30067035",
     success: function(data){
       var story = json.results[0].summary;
       $('p').html(story)
     }
});

更新:JSFIDDLE

3 个答案:

答案 0 :(得分:1)

你是说这个吗?

   var story = data.summary[0];
   $('p').html(story)

答案 1 :(得分:1)

你的结果是:

{
"title":"BBC News....",
"summary":[
    "They had...",
    "They want..",
    "The group..."
],
"source":"bbc.com"
}

这将有效:

$.ajax({
 type : "GET",
 crossOrigin: true,
 dataType : "jsonp",
 url : "http://clipped.me/algorithm/clippedapi.php?url=http://www.bbc.com/news/world-asia-china-30067035",
 success: function(data){
   var story = data.summary[0];
   $('p').html(story)
 }

});

答案 2 :(得分:1)

更好的功能是:

$.getJSON("http://clipped.me/algorithm/clippedapi.php?url=http://www.bbc.com/news/world-asia-china-30067035&callback=?", function(data) {
    var story = data.summary[0];
    $('p').html(story)
});

注意:我添加到结束'& callback =?'

然后是它的工作,但是。在您添加服务器PHP之前。 就像这样

<?php
    echo $_GET['callback'] . '(' . "{'title' : 'value'}" . ')';
?>

不要忘记,回调,它是为了安全的CrossDomain。