使用jQuery处理JSON数据

38 浏览
0 Comments

使用jQuery处理JSON数据

此问题已有答案:

将JSON字符串安全地转化为对象

我正在练习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": "

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.

\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数据的标准方法,感谢您的帮助!

admin 更改状态以发布 2023年5月24日
0
0 Comments

顾名思义,stringify将JSON转换为字符串。 JSON是原生JavaScript,根据您的示例数据:

[
    {
        "ID": 1127,
        "title": "Paul Rand",
        "content": "

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.

\n", "link": "https://quotesondesign.com/paul-rand-7/" } ]

您将得到一个对象数组(方括号内)(花括号中的对象)。 在这种情况下,数组中只有一个对象,因此您可以使用data [0]访问数组中的第一个对象,然后获取其content 属性:

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

0