fetch APIを使用してコード行数を減らす


🎯fetch API


📌 ajaxを使用する方法


ajaxを使用するにはいくつかの方法があります.
  • XMLHttpRequestオブジェクト
  • fetch api
  • jQuery
  • axiosライブラリ
  • 本稿では,1,2回のfetch apiの利点を比較する.

    📌 XMLHttpRequest


    最初の最も古典的な使い方.
    onreadystatechangeが使用されています.
    let xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let response = JSON.parse(xhr.response);
            console.log(response);
        }
    };
    
    xhr.open('get', 'https://yts.mx/api/v2/list_movies.json');
    xhr.send();
    https://yts.mxはjsonオブジェクトを提供する良いサイトです.
    上記のコードを実行すると、コンソールに出力されます.

    上記のコードをより簡単に変更する場合は、次のように変更できます.
    let xhr = new XMLHttpRequest();
    
    xhr.onload = () => {
        let response = JSON.parse(xhr.response);
            console.log(response);
    }
    
    xhr.open('get', 'https://yts.mx/api/v2/list_movies.json');
    xhr.send();

    📌 fetch


    fetch apiを使用しましょう.
    fetch('https://yts.mx/api/v2/list_movies.json')
        .then((response) => response.json())
        .then((json) => {
            console.log(json);
        });
    出力結果は上記と同じです.
    fetchはPromiseベースです.したがって、thenを使用してサーバから受信したデータを利用することができます.
    1行目はfetchでWebブラウザ「https://yts.mx/api/v2/list_movies.json」からデータを受信!お願いします.
    後で正常にデータを受信すれば.コールバック関数はthen()に掛けられます.
    low関数を使用しているので応答します.json()はすぐに戻り、次の.選択されます
    確かに、fetch apiを使用すると、XMLHttpRequestオブジェクトを使用するよりもコードの簡潔さと可読性が向上します.