JavaScriptでHTTPを利用してWebのファイルを取得する - XMLHttpRequestの利用 - JavaScript

JavaScriptでHTTPを利用し、インターネット(Web)のファイルを取得するコードを紹介します。

概要

JavaScriptでHTTPを利用しファイルを取得する場合にはXMLHttpRequestオブジェクトを利用します。XMLHttpRequestを用いるとJavaScript内からHTTPを利用してWeb上のファイルを取得することができ、ページ遷移なしで動的にコンテンツを読み込むことができます。

コード

以下のコードを記述します。

html ファイル

HTMLファイルです。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
  <script type="text/javascript">
    function getData() {
      //var xmlhttp = createXMLHttpRequest(); //旧バージョンのIEなどに対応する場合
      var xmlhttp = new XMLHttpRequest();

      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
          if (xmlhttp.status == 200) { 
            var elem = document.getElementById("output");
            elem.innerText = xmlhttp.responseText;
          } else {
            alert("status = " + xmlhttp.status);
          } 
        }
      }
      xmlhttp.open("GET", "textdata.txt");
      xmlhttp.send();
    }
    
    function createXMLHttpRequest(){
      if(window.XMLHttpRequest){return new XMLHttpRequest()}
      if(window.ActiveXObject){
        try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}
        try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}
        try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}
      }
      return false;
    }

  </script>
</head>
<body>
  <input id="Button_Get" type="button" value="取得" onclick="getData();" />
  <div>受信情報</div>
  <div id="output"></div>
</body>
</html>

textdata.txt

XMLHttpRequestで読み込むデータファイルです。上記のhtmlファイルと同じディレクトリに配置します。
テキストです。
あいうえお。
ABCDE

解説

  <input id="Button_Get" type="button" value="取得" onclick="getData();" />
HTMLの上記inputタグで記述された"取得"ボタンを押すとJavaScriptのgetData()関数を実行します。

function getData() {
  //var xmlhttp = createXMLHttpRequest(); //旧バージョンのIEなどに対応する場合
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) { 
        var elem = document.getElementById("output");
        elem.innerText = xmlhttp.responseText;
      } else {
        alert("status = " + xmlhttp.status);
      } 
    }
  }
  xmlhttp.open("GET", "textdata.txt");
  xmlhttp.send();
}
    
function createXMLHttpRequest(){
  if(window.XMLHttpRequest){return new XMLHttpRequest()}
  if(window.ActiveXObject){
    try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}
    try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}
    try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}
  }
  return false;
}
createXMLHttpRequest()関数はXMLHttpRequestオブジェクトを作成する関数です。最近のブラウザでは
var xmlhttp = new XMLHttpRequest();
のコードにより、XMLHttpRequestオブジェクトを作成できますが。古いバージョンのInternetExplorerでは対応していないため createXMLHttpRequest()関数を用意しています。

XMLHttpRequestオブジェクトを作成し
  xmlhttp.open("GET", "textdata.txt");
  xmlhttp.send();
のコードによりファイルの取得をします。openメソッドの第一引数がアクセスメソッド、第二引数が取得するファイルのパス(URL)になります。
処理は非同期で行われるため、サーバーからのレスポンスがあり、XMLHttpRequestオブジェクトのステータスが変わると下記のonreadystatechangeに設定された関数が呼び出されます。
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) { 
        var elem = document.getElementById("output");
        elem.innerText = xmlhttp.responseText;
      } else {
        alert("status = " + status.status);
      } 
    }

redyStateの値が4、ステータスコードが200の場合ファイルの取得ができたことになります。
ファイルの取得が確認できた後、取得したテキストを"output"をIDに持つ要素のinnerTextとして表示します。

実行結果

HTMLファイルを表示します。下図の画面が表示されます。


[取得]ボタンを押すと同じディレクトリに配置した"textdata.txt"ファイルを読み込みます。読み込みができると"textdata.txt"の内容が下部に表示されます。


ファイルが存在しない場合は下図のダイアログが表示されます。


JavaScriptでWeb上のファイルを取得することができました。
このページのキーワード
  • JSでHTTPを利用してWebのファイルを取得する - XMLHttpRequestの利用
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2017-09-04
作成日: 2013-08-28
iPentec all rights reserverd.