我想要一种简单的方法将文本和作者显示到HTML中,如下所示:
文本:仅仅通过观看就可以观察到很多东西
作者: Yogi Berra
在这里,我尝试用jQuery来实现它,除非我将text
从(data.text)
中删除,否则它在注销时会在屏幕和undefined
上返回空白。
$.ajax({
url: "https://type.fit/api/quotes",
method: "GET"
}).then(function(data) {
$("#text").text(data.text);
$("#author").text(data.author);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p id="text"></p>
<p id="author"></p>
</div>
我在这里错过了什么?
发布于 2021-02-10 09:13:27
数据是JSON格式的,因此需要进行分析。它也是一个数组,因此需要选择第二个元素来显示所选文本:
$.ajax({
url: "https://type.fit/api/quotes",
method: "GET"
}).then(function(data) {
data = JSON.parse(data);
$("#text").text(data[1].text);
$("#author").text(data[1].author);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p id="text"></p>
<p id="author"></p>
</div>
发布于 2021-02-10 09:14:50
data.text
访问数据。
$.ajax({
url: "https://type.fit/api/quotes",
method: "GET"
}).then(function(data) {
data = JSON.parse(data); // Added this code
$("#text").text(data[0].text); // Updated
$("#author").text(data[0].author); // Updated
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p id="text"></p>
<p id="author"></p>
</div>
奖励:如果您想显示来自JSON的所有数据,用ID在单个元素中打印它并不是最好的方法,请使用循环和动态DOM创建
发布于 2021-02-10 09:17:11
如果在console.log(data)
中执行.then,您将看到数据以字符串化的JSON形式出现。
因此,在使用数据之前,必须将数据返回到JSON本身。
const parsedData = JSON.parse(data);
然后,您将遇到另一个问题,因为数据不包含单个元素。这是一个数组。因此,要么从其中选择一个特定的元素,要么在其上循环。
$.ajax({
url: "https://type.fit/api/quotes",
method: "GET"
}).then(function(data) {
const parsedData = JSON.parse(data);
console.log(parsedData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
https://stackoverflow.com/questions/66133826
复制相似问题