【问题标题】:manipulating json data with jquery [duplicate]用jquery操作json数据[重复]
【发布时间】:2017-09-05 20:52:10
【问题描述】:

我正在练习 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 对象的 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 数据的标准方法,感谢所有帮助!

【问题讨论】:

    标签: javascript jquery json ajax


    【解决方案1】:

    顾名思义,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]访问数组中的第一个对象,然后得到它的@ 987654324@财产:

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

    【讨论】:

    • 你能澄清一下索引0吗?
    • 是的,我会编辑问题
    • 啊。我现在可以清楚地看到一切。谢谢您的帮助!!!使用 API 已经很棒了!!!!
    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多