关于javascript:使用jquery操作JSON数据

manipulating json data with jquery

本问题已经有最佳答案,请猛点这里访问。

我正在练习Ajax调用,访问返回的JSON数据时遇到问题。

我有以下代码

1
2
3
4
5
6
7
8
9
10
11
12
$('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
  });
});

哪些输出

1
2
3
4
5
6
7
8
9
10
11
[
{
"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>
"
,
"link":"https://quotesondesign.com/paul-rand-7/"
}
]

我只是想输出我的JSON对象的contentlink属性。我试过以下方法:

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

哪些输出

1
2
3
4
5
[{"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.


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

我正在寻找处理JSON数据的标准方法,谢谢您的帮助!


顾名思义,stringify将JSON转换为字符串。JSON是本机JavaScript,基于您的示例数据:

1
2
3
4
5
6
7
8
9
10
11
[
    {
       "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>
"
,
       "link":"https://quotesondesign.com/paul-rand-7/"
    }
]

您返回一个对象数组(方括号中)(大括号中)。在这种情况下,它只是数组中的一个对象,因此您使用data[0]访问数组中的第一个对象,然后获取其content属性:

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