我正在练习Ajax调用,并且在访问返回的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对象的content
和link
属性。我尝试了以下内容:
$('.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数据的标准方法,感谢所有帮助!
答案 0 :(得分: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/"
}
]
你得到一个对象的数组(方括号中)(花括号中)。在这种情况下,它只是数组中的一个对象,所以你用{{1}访问数组中的第一个对象然后获取其data[0]
属性:
content