【问题标题】:how do i extract my data from json file so i can put it inner html?我如何从 json 文件中提取我的数据,以便将其放入内部 html?
【发布时间】:2021-11-09 21:45:52
【问题描述】:

我正在尝试从 JSON 文件中提取我的数据,我什至使用 .map() 来映射数据,但它最终显示 result.map() 不是定义函数的错误。我如何显示提取数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON Test</title>
</head>
<body>
    <div id="myData"></div>
        <!-- Here a loader is created which 
             loads till response comes -->
        <div class="d-flex justify-content-center">
            <div class="spinner-border" 
                 role="status" id="loading">
                <span class="sr-only">Loading...</span>
            </div>
        </div>
        <h1>Registered Employees</h1>
        <!-- table for showing data -->
        <table id="employees"></table>
    </body>
    <script src="api1-2.js"></script>>
</html>

【问题讨论】:

标签: javascript html css json


【解决方案1】:

您需要使用response.json() 而不是response.text()。

response.json() 和 response.text() 都返回一个 Promise,但 response.json() 将该 Promise 解析为一个 JavaScript 对象,而 response.text() 将该 Promise 解析为一个字符串。

参考资料:

【讨论】:

    【解决方案2】:

    将response.txt() 替换为response.json() 以解析对json 对象的api 响应。使用 response.text() 你的结果是字符串,所以它没有 map 方法,因此 undefined 错误。

    fetch("https://v1.nocodeapi.com/OPENSOURCE12/instagram/gflSSOQjdOHsVnhT", requestOptions)
        .then(response => response.json()) // ? modified
        .then(result => {console.log(result)})
        .catch(error => console.log('error', error));
    

    【讨论】:

    • 它仍然说 .map 不是函数
    • 数组有 .map 功能。检查您尝试使用 .map func 迭代的内容是否为数组。如果你正在尝试 result.map 并且结果是{ } 格式,你会得到同样的错误
    • 所以 jason 文件中的数组被命名为数据,所以我尝试使用 result.data.map() ,我尝试删除该对象,但我在这里没有找到
    • 明确一点,result.data 是数组[ ] 还是对象{ }?
    • 结果是一个对象,{}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2018-09-10
    • 2014-08-14
    • 2018-03-26
    • 2016-05-15
    相关资源
    最近更新 更多