APIを取得する方法はいくつかありますが、
今回は【XMLHttpRequest】を使って取得してみます。
サンプル
HTML
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>地震情報</title>
</head>
<body>
<h1>APIで地震情報</h1>
<div id="wordpress_blog">
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</body>
</html>
JavaScript
//HTML作成
const apiHtml = (jsons) => {
$("#wordpress_blog").html("");
for (let i = 0; jsons.length > i; i++) {
let name = null;
let maxScale = null;
let magnitude = null;
let time = null;
let year = null;
let mon = null;
let day = null;
let hour = null;
let minut = null;
let second = null;
let weeks = ['日','月','火','水','木','金','土'];
const log = jsons[i];
if(log.earthquake.hypocenter.name != ""){
name = log.earthquake.hypocenter.name;
}else{
name = "不明";
}
if(log.earthquake.maxScale != ""){
maxScale = log.earthquake.maxScale / 10;
}else{
maxScale = "不明";
}
if(log.earthquake.hypocenter.magnitude != ""){
magnitude = log.earthquake.hypocenter.magnitude;
}else{
magnitude = "不明";
}
if(log.time != ""){
time = new Date(log.time);
year = time.getFullYear();
mon = time.getMonth() + 1;
day = time.getDate();
hour = time.getHours();
minut = time.getMinutes();
second = time.getSeconds();
time = year + "年" + mon + "月" + day + "日"+ "(" + weeks[time.getDay()] + ")" + hour + "時" + minut + "分" + second + "秒";
}else{
time = "不明";
}
$("#wordpress_blog").append(
"<table>" +
"<tr><td rowspan = '5'>" + (i + 1) + "</td></tr>" +
"<tr><th>場所</th><td>" + name +
"</td></tr><tr><th>震度</th><td>" + maxScale +
"</td></tr><tr><th>マグニチュード</th><td>" + magnitude +
"</td></tr><tr><th>時間</th><td>" + time + "</td></tr>" +
"</table>"
);
console.log(time);
}
}
// オブジェクトを作成
let apiHttps = new XMLHttpRequest();
// イベントで処理の状況変化を監視
apiHttps.onreadystatechange = function () {
if (this.readyState == 0) {
console.log("UNSENT:初期状態");
}
if (this.readyState == 1) {
console.log("OPENED:openメソッド実行");
}
if (this.readyState == 2) {
console.log("HEADERS_RECEIVED:レスポンスヘッダー受信");
}
if (this.readyState == 3) {
console.log("LOADING:データ受信中");
}
if (this.readyState == 4) {
console.log("DONE:リクエスト完了");
}
if (this.readyState == 4 && this.status == 200) {
const logs = this.responseText;
const jsons = JSON.parse(logs);
apiHtml(jsons);
}
};
// メソッドとアクセスする場所を指定
apiHttps.open("GET", "https://api.p2pquake.net/v2/jma/quake", false);
// 送信
apiHttps.send();
CSS
table{
margin-bottom: 50px;
border-collapse: collapse;
}
table th,table td{
border: solid 1px #000;
padding: 5px;
text-align: left;
}