0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

FetchAPI の使い方 (get)

Last updated at Posted at 2022-04-14

次のページを参考にしました。
[HTML5] Fetch API で GET/POST で通信する
World Time API

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<title>Fetch API Sample1</title>
<style>
    #jst{ text-decoration:underline; font-weight:bold; }
    #result{ display:none; }
</style>
</head>
<body>

<section>
  <h1>Fetch API Sample1</h1>

  <div id="nowloading">
    ...サーバから時間を取得中
  </div>
  <div id="result">
    現在の時間は <time id="jst"></time> です。
  </div>
</section>
<br />
<script src="fetch_get.js"></script>

<hr />
Apr/14/2022<br /> 
</body>
</html>
fetch_get.js
// ---------------------------------------------------------------
//	fetch_get.js
//
//						Apr/14/2022
// ---------------------------------------------------------------
/*
** [event] ページ読み込み完了時に実行
*/

window.onload = ()=>{

	console.error("*** fetch_get.js ***")

	const URL = "https://worldtimeapi.org/api/timezone/Asia/Tokyo"

  //--------------------------------------
  // 現在時間を取得する
  //--------------------------------------
fetch(URL)
    .then((res)=>{
      if( ! res.ok ) {
        throw new Error(`Fetch: ${res.status} ${res.statusText}`);
      }
      return( res.json() );
    })
    .then((json)=>{
	console.error(json.datetime)
	document.querySelector("#jst").innerHTML = json.datetime

      // 表示を切り替える
	document.querySelector("#nowloading").style.display = "none";
	document.querySelector("#result").style.display = "block";
    })
    .catch((error)=>{
	alert("エラーが発生しました");
	console.error(`[FetchAPI] ${error}, ${URL}`);
    })
}


// ---------------------------------------------------------------

ブラウザーでアクセス
fetch_get.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?