元Webデザイナー兼コーダーの備忘録

ウェブデザインやプログラミング、ブログのカスタマイズなどについてアウトプットしています。

 メニュー

» HTML入門のまとめはこちらです。

【jQuery】Ajaxで外部データを取得する

jQueryAjaxを使って、外部データ(JSONXML、HTML)を取得する方法を見ていきます。

JSONの取得

ex.)気象庁のサイトから東京都の天気予報のデータをJSON形式で取得

取得先:https://www.jma.go.jp/bosai/forecast/data/overview_forecast/130000.json

$(function(){
  const url = "https://www.jma.go.jp/bosai/forecast/data/overview_forecast/130000.json";
  $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    // 取得に成功したときの処理
    success:function(data){
      console.log(JSON.stringify(data, null, 2));

      const publishingOffice = data.publishingOffice; //data.キー名で値を参照
      console.log(publishingOffice);
    },
    // 完了したときの処理
    complete:function(){
      console.log("通信が完了しました。");
    },
    // 失敗したときの処理
    error:function(){
      console.log("通信に失敗しました。");
    }
  });
});

dataの中にJSONデータが入ります。data.キー名で値を参照できます。

XML(RSS)の取得

ex.)当ブログのRSSの取得

取得先:https://shiroyuki2020.hatenablog.com/rss

<div id="result"></div>
$(function(){
  const url = "RSSを配信しているURL";
  $.ajax({
    type: "GET",
    url: url,
    dataType: "xml",
    // 取得に成功したときの処理
    success:function(data){
      $("item", data).each(function(){
        const title = $("title", this).text();
        const link = $("link", this).text();
        const description = $("description", this).text();
        const pubDate = $("pubDate", this).text();
        const category = $("category", this).text();

        // ブラウザ表示
        $("#result").append(`
          <ul>
            <li><a href="${link}">${title}</a></li>
            <li>${pubDate}</li>
            <li>${category}</li>
          </ul>
        `);
      });
    },
    // 完了したときの処理
    complete:function(){
      console.log("通信が完了しました。");
    },
    // 失敗したときの処理
    error:function(){
      console.log("通信に失敗しました。");
    }
  });
});

HTMLの取得

ex.)当ブログのHTMLの取得

取得先:https://shiroyuki2020.hatenablog.com/

このサンプルでは、新しいAjaxの書き方で記述します。

$(function(){
  const url = "HTMLを取得したいURL";
  $.ajax({
    type: "GET",
    url: url,
    dataType: "html"
  }).done(function(data){  // 取得に成功したときの処理
    const title = $("#title", data).text();
    console.log(title);
  }).fail(function(){  // 失敗したときの処理
    console.log("通信に失敗しました。");
  }).always(function(){    // 常に実行する処理
    console.log("通信が完了しました。");
  });
});

HTMLを取得できないサイトもあります。

まとめ

AjaxJSONXML、HTMLのデータを取得できることが確認できました。これで、Web APIを利用できます。

参考

» HTML入門のまとめはこちらです。