たぼさんの部屋

いちょぼとのんびり

XMLHttpRequestの基本(GET)でtxtを読む

"use strict"
( function() {

   function init() {
      alert("start");
      xhrConnect();
   };
   function xhrConnect() {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
         if (xhr.readyState == 4) {// DONE
            if (xhr.status == 200) {// OK
               alert(xhr.responseText);
            } else {
               alert("status = " + xhr.status);
            }
         }
      };
      xhr.open("GET", "hoge.txt");
      xhr.send();
   };
   if (document.body) {
      init();
   } else {
      document.addEventListener("DOMContentLoaded", init);
   };
}());