Fetch JSON函数未正常工作。JavaScript

huangapple go评论71阅读模式
英文:

Fetch JSON function not working properly. JavaScript

问题

I have created a function named fetchJSONData() that is supposed to return a JavaScript object from the URL you give it, and when you console.log the output, it works as expected, but when I try to access a property from the returned object, it shows undefined as the property value.

Here is the small json file I am using:

{
    "headerText": "Lorem Ipsum",
    "subText": "lorem ipsum dolor sit amet....."
}

Here is a very basic example code snippet:

async function fetchJSONData(url) {
    var response = await fetch(url);
    var data = await response.json();
    console.log(data);
    return data;
}

var textTest = fetchJSONData("https://jsonplaceholder.typicode.com/posts/1");
var test01 = document.getElementById("test01");
var test02 = document.getElementById("test02");

window.onload = function() {
    // Returns undefined
    test01.innerText = textTest.title;
    test02.innerText = textTest.body;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1 id="test01">blank</h1>
    <p id="test02">blank</p>
</body>
</html>

You can see when I try to access the variables, the html elements show the value is undefined.

英文:

I have created a function named fetchJSONData() that is supposed to return a JavaScript object from the URL you give it, and when you console.log the output, it works as expected, but when I try to access a property from the returned object, it shows undefined as the property value.

Here is the small json file I am using:

{
    &quot;headerText&quot;: &quot;Lorem Ipsum&quot;,
    &quot;subText&quot;: &quot;lorem ipsum dolor sit amet.....&quot;
}

Here is a very basic example code snippet:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

async function fetchJSONData(url) {
    var response = await fetch(url);
    var data = await response.json();
    console.log(data);
    return data;
}

var textTest = fetchJSONData(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;);
var test01 = document.getElementById(&quot;test01&quot;);
var test02 = document.getElementById(&quot;test02&quot;);

window.onload = function() {
    // Returns undefined
    test01.innerText = textTest.title;
    test02.innerText = textTest.body;
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1 id=&quot;test01&quot;&gt;blank&lt;/h1&gt;
    &lt;p id=&quot;test02&quot;&gt;blank&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

You can see when I try to access the variables, the html elements show the value is undefined.

答案1

得分: 2

以下是翻译好的部分:

首先,您试图访问 textTest.titletextTest.body。您的JSON文件中的JSON结构不包含 titlebody 属性,因此它们将为 undefined

另一方面,您的代码片段引用了具有不同JSON结构的URL。如果这是您正在使用的内容,属性名称应该是正确的。

但是,当 window.onload 事件处理程序运行时,从 fetchJSONData 返回的Promise尚未解析(而且它返回一个Promise,因此您需要使用 await 进行等待)。
您可以通过将DOM更新逻辑移到 fetchJSONData 函数中来解决此问题:

async function fetchJSONData(url) {
    var response = await fetch(url);
    var data = await response.json();
    var test01 = document.getElementById("test01");
    var test02 = document.getElementById("test02");
    test01.innerText = data.title;
    test02.innerText = data.body;
    console.log(data);
    return data;
}

var textTest = fetchJSONData("https://jsonplaceholder.typicode.com/posts/1");

window.onload = function() {
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <h1 id="test01">blank</h1>
    <p id="test02">blank</p>
</body>
</html>

希望这有所帮助。

英文:

First of all, you are trying to access textTest.title and textTest.body. The JSON structure in your JSON file does not contain the title and body properties, so they will be undefined.

Your code snippet, on the other hand, refers to a URL with a different JSON structure. If this is what you're using, the property names should be OK.

But, when the window.onload event handler runs, the promise returned from fetchJSONData will not have resolved (also, it returns a promise, so you would have to await it.).
You can solve this by moving your DOM update logic into the fetchJSONData function:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

async function fetchJSONData(url) {
    var response = await fetch(url);
    var data = await response.json();
    var test01 = document.getElementById(&quot;test01&quot;);
    var test02 = document.getElementById(&quot;test02&quot;);
    test01.innerText = data.title;
    test02.innerText = data.body;
    console.log(data);
    return data;
}

var textTest = fetchJSONData(&quot;https://jsonplaceholder.typicode.com/posts/1&quot;);

window.onload = function() {
}

<!-- language: lang-html -->

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1 id=&quot;test01&quot;&gt;blank&lt;/h1&gt;
    &lt;p id=&quot;test02&quot;&gt;blank&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月22日 06:11:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定