2017-04-10 101 views
0

我正在练习Ajax调用,并且在访问返回的JSON数据时遇到问题。用jquery操纵json数据

我有以下

$('button').on('click', function() {  
    $.ajax({ 
    url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', 
    success: function(data) { 
     console.log(data); 
    }, 
    error: function() { 
     console.log('error occured'); 
    }, 
    cache: false 
    }); 
}); 

下面的代码输出

[ 
{ 
"ID": 1127, 
"title": "Paul Rand", 
"content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear. </p>\n", 
"link": "https://quotesondesign.com/paul-rand-7/" 
} 
] 

我只是想给我的输出JSON对象的contentlink性能。我已经试过如下:

$('.message').html(JSON.stringify(data)); 

其输出

[{"ID":2294,"title":"Josh Collinsworth","content":" 
You do not need to have a great idea before you can begin working; you need to begin working before you can have a great idea. 

\n","link":"https://quotesondesign.com/josh-collinsworth-3/"}] 

我试图寻找标准的方法来处理JSON数据,感谢所有帮助!

回答

3

顾名思义,stringify将JSON转换为字符串。 JSON是本地JavaScript,并根据您的样本数据:

[ 
    { 
     "ID": 1127, 
     "title": "Paul Rand", 
     "content": "<p>Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear. </p>\n", 
     "link": "https://quotesondesign.com/paul-rand-7/" 
    } 
] 

你回来对象数组(方括号中)(在大括号)在这种情况下,它在阵列中只有一个对象,所以你与data[0]访问数组中的第一个对象,然后获取其content属性:

$('.message').html(data[0].content); 
+0

u能澄清指数0? –

+0

是的,我会编辑问题 – miken32

+0

啊。我现在可以清楚地看到一切。谢谢您的帮助!!!使用API​​的工作已经很棒了! –