【问题标题】:Get data from Json by using javascript (jsonplaceholder)使用 javascript (jsonplaceholder) 从 Json 获取数据
【发布时间】:2018-05-06 14:44:17
【问题描述】:

我一直在尝试在 HTML 页面上打印 Json 文件的数据。我需要导入这些数据:

https://jsonplaceholder.typicode.com/posts/1

我试图使用此代码从文件中获取数据:

https://github.com/typicode/jsonplaceholder#how-to

这是我在函数中写的:

JS:

function req1() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(json => console.log(json))
        // we print the title and the body of the post recived
    var title = response.data.title;
    var body = response.data.body
    document.getElementById("printTitle").innerHTML = title
    document.getElementById("printBody").innerHTML = body
}

HTML:

<div class="news-btn-div" data-tab="news-2" onclick="req1()">2</div>

    <div id="news-2" class="news-content-container-flex">
      <div class="news-title">
        <span id="printTitle">
        </span>
      </div>
      <div class="news-content-1">
        <span id="printBody">
        </span>
      </div>
    </div>

所以我应该在单击 .news-btn-div DIV 后获取数据,但我不知道我在哪里犯了错误。

printTitle 和#printBody DIVS 应该填充数据。

有什么建议吗?

这是我的 Jsfiddle:

https://jsfiddle.net/matteous1/ywh0spga/

【问题讨论】:

    标签: javascript json


    【解决方案1】:

    您在获取的第二次回调中出现了一些错误。您需要从 json 对象(您给 response.json() 回调的名称)获取数据。然后访问json 的适当元素以打印它们。 正如@Clint 指出的那样,您在使用收到的数据(titlebody)之前关闭了回调,您试图在其范围之外访问它。

    function req1() {
      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => response.json())
        .then(json => {
          const title = json.title;
          const body = json.body;
          document.getElementById("printTitle").innerHTML = title;
          document.getElementById("printBody").innerHTML = body;
        });
    }
    
    req1();
    <div class="news-btn-div" data-tab="news-2" onclick="req1()">2</div>
    
        <div id="news-2" class="news-content-container-flex">
          <div class="news-title">
            TITLE
            <span id="printTitle">
            </span>
          </div>
          <div class="news-content-1">
            BODY
            <span id="printBody">
            </span>
          </div>
        </div>

    【讨论】:

    • 要添加到这个答案, fetch 是异步的,因此任何处理数据的代码都必须在回调中。外部的任何东西都会在请求完成之前触发。
    • 您好,非常感谢您的回答,我还尝试创建多个按钮并在单击第二个时显示第二个帖子,当我单击第三个时显示第三个帖子。为了做到这一点,我复制了该功能,但我不明白如何将第一个用作默认值。我想在每次加载页面时打开第 1 号帖子,然后当我点击其他按钮时,我会看到其他帖子。目前,当我加载页面时,我会收到随机帖子。我正在编辑我的问题以使其更清楚。
    • @Matteo,你最好打开一个新问题,带着你必须避免与旧问题混淆的新问题。
    猜你喜欢
    • 2010-10-24
    • 2011-12-27
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    相关资源
    最近更新 更多