[英]Get data from Json by using javascript (jsonplaceholder)
我一直在嘗試在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,我應該獲取數據,但我沒有弄錯的地方。
有什么建議嗎?
這是我的Jsfiddle:
您的提取的第二個回調中有一些錯誤。 您需要從json
對象(您給response.json()
回調指定的名稱)獲取數據。 然后訪問json
適當元素以進行打印。 正如@Clint指出的那樣,您在使用接收到的數據( title
, body
)之前關閉了回調,您試圖在其作用域之外訪問它。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.