LoginSignup
1
0

More than 1 year has passed since last update.

[JavaScript]fetch メソッド

Last updated at Posted at 2021-08-12

コード

sample.html
<html>
<body>
    <input id="station">
    <button id="button" onclick="fetchAPI()">検索</button>

    <div id="stationList">
    </div>

    <script>
        function fetchAPI(){
            console.log("処理を開始します");
            const name = document.getElementById('station').value
            console.log(`入力された駅名: ${name}`);

            // fetch メソッドは Promise を返す
            fetch(`https://api.ekispert.jp/v1/json/station?key=YOUR_ACCESS_KEY&name=${name}`) 
            .then(function(result){
                return result.json();
            }).then(function(result){
                return result.ResultSet.Point;
            }).then(function(result){
                var count = 0;
                var station = "";
                for (element of result){
                    console.log(element.Station.Name);
                    count += 1;
                    station += `${element.Station.Name}\n`;
                }
                document.getElementById('stationList').innerText = `${station}駅候補計${count}件\n`;
            }).catch(function(){
                alert("エラーが発生しました");
                console.log("エラーが発生しました");
            }).finally(function(){
                console.log("処理を終了します"); // エラー発生有無関わらず、最後に必ずこの処理を実行する
            })

        }
    </script>
</body>
</html>

実行結果

テキストフィールドに「大阪」を入力し、「検索」ボタンをクリック
スクリーンショット 2021-08-13 1.24.41.png

参考資料

非同期処理:コールバック/Promise/Async Function - JavaScript Primer
駅すぱあとWebサービス

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