简体   繁体   中英

Get data from Json by using javascript (jsonplaceholder)

I've been trying to print the Json file's data on a HTML page. I need to import these data:

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

I was trying to use this code to get the data from the file:

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

This is what I wrote in my function:

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>

So I should get the data once I click on .news-btn-div DIV but I don't get where I'm making the mistake.

printTitle and #printBody DIVS should be populated with data.

Any advice?

Here my Jsfiddle:

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

You had some errors in your second callback of the fetch. You need to get the data from json object (name you gave to the response.json() callback). Then access to proper elements of json in order to print them. As @Clint pointed out, you closed the callback before using the data received ( title , body ), you were trying to access to it outside of its scope.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM