アプリケーション開発ポータルサイト
ServerNote.NET
Amazon.co.jpでPC関連商品タイムセール開催中!
カテゴリー【JavaScript
JavaScriptで外部URLのファイルをダウンロードしてデータを取得する
POSTED BY
2023-07-08

XMLHttpRequest, jQuery.ajax, fetchいずれかの方法があるが、同期・非同期が簡単に使い分けられるjQuery.ajaxがおすすめ。

https://api.jquery.com/jquery.ajax/

以下のような、Solidity ERC-721 abi.jsonファイルをダウンロードするものとする。

JSONabi.jsonGitHub Source
[
  {
    "inputs": [
      {
        "internalType": "address",
        "name": "owner",
        "type": "address"
      }
    ],
    "name": "balanceOf",
    "outputs": [
      {
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
  {
    "inputs": [
      {
        "internalType": "uint256",
        "name": "tokenId",
        "type": "uint256"
      }
    ],
    "name": "ownerOf",
    "outputs": [
      {
        "internalType": "address",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  },
]

同期(その場で終わるまで待ってから次を実行)で使う場合

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>//<![CDATA[

var abi_json = null;

console.log("before ajax call");

$.ajax({
    type: 'GET',
    url: 'abi.json',
    data: 'a=b&c=d',
    async : false,
  dataType: 'text',
    success: function(data) {
    console.log("success ajax call");
        if(data != null) {
            console.log(data);
            abi_json = JSON.parse(data);
            console.log(abi_json);
        }
    }
});

console.log("after ajax call");

//]]></script>

typeにはメソッドを指定、urlにはこのhtmlからの相対パスか、httpsから始まる絶対パスを指定。
dataにはURLに渡すパラメータを指定。URLがCGIプログラムである場合などに指定。
asyncをfalseに設定することで、同期通信となり、ダウンロードが終わるまで次へ行かない。
dataTypeには文字列でダウンロード対象のファイルタイプを指定する。
textを指定すると、テキストデータとして持ってくるので、consoleで確認したあと、あらためてJSON.parseして文字列→JSON変換するのがおすすめ。
いきなりデータタイプにjsonを指定することもできる。その場合JSON.parseは不要で、dataにはダイレクトにJSON型のデータが入る。

実行結果console.log

before ajax call
success ajax call
after ajax call

before→success→afterと、通信が終わるのを待ってから順番に実行されているのが確認できる。

非同期(バックグラウンドで実行しながら)で使う場合

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>//<![CDATA[

var abi_json = null;

console.log("before ajax call");

$.ajax({
    type: 'GET',
    url: 'abi.json',
    data: 'a=b&c=d',
    async : true,
  dataType: 'text',
    success: function(data) {
    console.log("success ajax call");
        if(data != null) {
            console.log(data);
            abi_json = JSON.parse(data);
            console.log(abi_json);
        }
    }
});

console.log("after ajax call");

//]]></script>

asyncをtrueに設定することで、非同期通信となり、バックグラウンドへ移行しすぐ次の処理へ行く。
終わったらsuccessがあとから呼ばれることになる。

実行結果console.log

before ajax call
after ajax call
success ajax call

before→after→successと、通信が終わるのを待たずにすぐ次へ行って後からsuccessが呼ばれているのが確認できる。
よって、グローバル変数abi_jsonがnullの場合まだ通信が終わっていないかエラーかということなので、そこを判定して処理を分ける。

※本記事は当サイト管理人の個人的な備忘録です。本記事の参照又は付随ソースコード利用後にいかなる損害が発生しても当サイト及び管理人は一切責任を負いません。
※本記事内容の無断転載を禁じます。
【WEBMASTER/管理人】
自営業プログラマーです。お仕事ください!
ご連絡は以下アドレスまでお願いします★

☆ServerNote.NETショッピング↓
ShoppingNote / Amazon.co.jp
☆お仲間ブログ↓
一人社長の不動産業務日誌
【キーワード検索】