gpt4 book ai didi

javascript - 使用 jquery 操作 json 数据

转载 作者:行者123 更新时间:2023-11-28 18:02:24 26 4
gpt4 key购买 nike

我正在练习 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/"
}
]

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

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

最佳答案

顾名思义,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);

关于javascript - 使用 jquery 操作 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43329475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com