LoginSignup
0
0

More than 3 years have passed since last update.

OpenWeatherMapのapiの復習

Last updated at Posted at 2020-12-15

今回のapiの部部に関わっているのはここ

let xhr = new XMLHttpRequest(); //1

    xhr.open('GET', requestUrl);//2

    xhr.send();

    xhr.onreadystatechange = function () {//3
        if (xhr.readyState == 4) {
            ShowTodayWeather(xhr.responseText);//4
        }
    }

    function ShowTodayWeather(response) {
        let obj = JSON.parse(response) //5
        let weather = obj.weather[0].description; //6
        let city = obj.name;
        let temp = obj.main.temp;
        let humi = obj.main.humidity;
        let icon = obj.weather[0].icon;

        console.log("現在" + city + "の天気は" + weather);
        console.log(`気温は ${temp} 度です`);
        console.log(icon)

        const Tem = document.getElementById("tem");
        const Hum = document.getElementById("hum");

        Tem.innerHTML = temp
        Hum.innerHTML = humi
        Icon.setAttribute('src','http://openweathermap.org/img/w/'+icon+'.png')   
    }

mdnではこちら

1つずつ見ていく

1ではXMLHttpRequestオブジェクトを作成
newに関しては別でも勉強してまとめた。

2ではGETメソッドを使ってローカルサーバ上のurlを指定している。
情報を取得する時にはGET
情報を送信する時にはPOSTメソッドを使う。

3では1での処理の状況を監視している。
ここのreadyStateが4なのは4がリクエスト処理の完了を表すからである。

4のresponseTextはxhrのサーバーから受け取ったテキストを返している。

mdn
https://developer.mozilla.org/ja/docs/Web/API/XMLHttpRequest/responseText

5のJSON.parseはjsonデータで受け取った天気情報をjavascriptで扱えるようにするメソッドである。

もしJavascriptからjsonデータにしたいときにはJSON.stringifyメソッドを使う。

これらをデコード・エンコードと言う。

6では日本語で取得するために最後descriptionとつけている。

それ以下は公式ドキュメントを参考にデータを取得した。

参考サイト
https://www.sejuku.net/blog/47716
https://reffect.co.jp/html/xmlhttprequest-basic

0
0
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
0