XMLファイルを読み込む
サーバー上に置かれたXMLファイルを非同期で読み込んでダイアログ表示します。
サンプル
サーバテキスト(UTF-8)
<?xml version="1.0" encoding="utf-8"?> <root> <data>サーバー上のXMLデータです。</data> </root>
クライアントソース
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.1 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS" /> <meta http-equiv="Content-Style-Type" content="text/css" /> <title></title> <script type="text/javascript"> // クロスブラウザに対応したXMLHttpRequestオブジェクトを取得 function createHttpObject(){ try{ if (window.XMLHttpRequest){ // Win(moz1,ff1,op8,ie7),Mac,Linux httpObj = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Win(ie4,5,6) try { httpObj = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e1) { httpObj = new ActiveXObject("Microsoft.XMLHTTP"); } } else { httpObj = null; } }catch(e2){ httpObj = null; } return httpObj; } function submitReq(){ // XMLHttpRequestオブジェクト取得 httpObj = createHttpObject(); if (httpObj){ // GETメソッドでsample101.txtファイルを非同期で開く httpObj.open("GET","../data/sample102.xml",true); httpObj.onreadystatechange = function(){ // 状態が変わったときに実行する処理を記述 if (httpObj.readyState==4){ if (httpObj.status==200){ // 正常に受信完了できたときXML DOMとして読み込み処理する var xmlDoc = httpObj.responseXML; // 要素名でアクセスし var data = xmlDoc.getElementsByTagName("data"); // 要素値をメッセージ表示する。 // (この例の場合、要素数が1つと解っているので(0)としている) alert(data(0).text); }else{ alert("データ読み込みに失敗しました。("+httpObj.status+":"+httpObj.statusText+")"); return; } } } // 送信処理実行 httpObj.send(''); } } </script> </head> <body> <input id="Button1" type="button" value="サーバ上のXMLファイルを読み込みます" onclick="submitReq();" /> </body> </html>