2012年9月2日日曜日

XMLHttpRequestの最小サンプル

XMLHttpRequestの最小サンプルを作ってみた。

▽HTML側
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    
    <script type="text/javascript">
    //<![CDATA[
    function onLoad() {
      var xmlhttp = false;
      if(typeof ActiveXObject != "undefined"){
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          xmlhttp = false;
        }
      }
      if(!xmlhttp && typeof XMLHttpRequest != "undefined") {
        xmlhttp = new XMLHttpRequest();
      }

      xmlhttp.open("GET", "./test.xml");
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          var disp = document.getElementById("disp");
          var xmlDoc = xmlhttp.responseXML;
          disp.innerHTML = xmlDoc.getElementsByTagName('test')[0].firstChild.nodeValue;
        }
      }
      xmlhttp.send(null);
    }
    //]]>
    </script>
  </head>
  <body onload="onLoad()">
    <div id="disp">
</div>
</body>
</html>
▽取得するXML
<?xml version="1.0" encoding="UTF-8"?>
<test>ABCDEF</test>
▽実行結果
ABCDEF
▽課題
1.  ローカルのフォルダにファイルを置いただけでは動かない。Webサーバへのアップロードが必要。
2. XMLの値を変更してHTMLファイルをリロードしても、キャッシュのせいで値が更新されない。