gpt4 book ai didi

javascript - 解析来自 REST API 调用的 JSON 响应

转载 作者:行者123 更新时间:2023-12-03 00:33:59 25 4
gpt4 key购买 nike

我对使用 API 还很陌生。

我正在尝试获取响应文本并将其中的信息排序到卡片的不同区域。我并不是要求快速回答,而是要求一些我可以查看以充分理解的文档。

var stat = document.getElementById('infoboxName');
var promise1 = new Promise(function(resolve, reject) {
setTimeout(function() {

var xhr = new XMLHttpRequest(),
method = "GET",
url = "https://www.anapioficeandfire.com/api/characters/124";

xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
stat.innerHTML = xhr.responseText;
resolve("resolve");

}
};
xhr.send();
}, 300);
});

promise1.then(function(value) {
console.log(value);


});
<div id='infoboxName'></div>

响应输出

{
"url": "https://www.anapioficeandfire.com/api/characters/124",
"name": "Antario Jast",
"gender": "Male",
"culture": "",
"born": "",
"died": "",
"titles": [
"Lord"
],
"aliases": [
""
],
"father": "",
"mother": "",
"spouse": "https://www.anapioficeandfire.com/api/characters/616",
"allegiances": [
"https://www.anapioficeandfire.com/api/houses/212"
],
"books": [
"https://www.anapioficeandfire.com/api/books/2",
"https://www.anapioficeandfire.com/api/books/3",
"https://www.anapioficeandfire.com/api/books/5",
"https://www.anapioficeandfire.com/api/books/8"
],
"povBooks": [],
"tvSeries": [
""
],
"playedBy": [
""
]
}

最佳答案

您真正想做的是解析该响应,为此,您可以使用 JSON.parse 它将 JSON 字符串转换为 JS 对象。

解析该 JSON 字符串后,您可以使用 namegender 等特定属性访问数据。

另一方面,我认为您根本不需要 setTimeout

此示例解析 JSON 字符串并获取 namegender,同样通过函数 resolve 我传递将 JSON 字符串解析为 JS 对象。

var nameElement = document.getElementById('name');
var genderElement = document.getElementById('gender');

var promise1 = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest(),
method = "GET",
url = "https://www.anapioficeandfire.com/api/characters/124";

xhr.open(method, url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(JSON.parse(xhr.responseText));
}
};
xhr.send();
});

promise1.then(function(value) {
nameElement.textContent = value.name;
genderElement.textContent = value.gender;
});
<div id='infoboxName'>
<span id='name'></span>
<p/>
<span id='gender'></span>
</div>

关于javascript - 解析来自 REST API 调用的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53733231/

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