ユーザ用ツール

サイト用ツール


ajax:xmlhttprequest:sample

文書の過去の版を表示しています。


XMLHttpRequestサンプルコード

非同期通信のサンプルコードと解説。

function testXMLHttpRequest(){
    /* XMLHttpRequestオブジェクト作成 */
    var xmlhttp = createXmlHttp();
    if (xmlhttp == null) {
        window.alert("XMLHttpRequest非対応のブラウザです。");
    }
 
    /* レスポンスデータ処理用のコールバック関数を設定 */
    xmlhttp.onreadystatechange = handleHttpEvent;
 
    /* レスポンスデータ処理用のコールバック関数を定義 */
    function handleHttpEvent(){
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                window.alert(xmlhttp.responseText);   //レスポンスデータを表示します。
            } else {
                window.alert("通信エラーが発生しました。");
            }
        }
    }
 
    /* HTTPリクエスト実行 */
    xmlhttp.open("GET", "echo.cgi" , true);
    xmlhttp.send(null);
}
 
function createXmlHttp(){
    if (window.XMLHttpRequest) {             // Mozilla, Firefox, Safari, IE7
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {       // IE5, IE6
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");    // MSXML3
        } catch(e) {
            return new ActiveXObject("Microsoft.XMLHTTP"); // MSXML2まで
        }
    } else {
        return null;
    }
}

MSXML

POSTメソッドを実行する場合は、「HTTPリクエスト実行」の部分を以下のように修正

    xmlhttp.open("POST", "/script/ajax2.cgi" , true);
    xmlhttp.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
    xmlhttp.send(postdata);

postdataは、以下のようなクエリ文字列を使う。値はURLエンコーディングされている必要がある。

key1=value1&key2=value2&key3=value3

XMLHttpRequestは、その名の通り本来はXMLデータを送信するオブジェクトで、XMLデータを直接ポストできる。

var xml;
if (window.ActiveXObject) {
    xml = new ActiveXObject("Microsoft.XMLDOM");
} else if (document.implementation) {
    xml = document.implementation.createDocument("" , "" , null);
} else {
    return;
}
xml.appendChild(xml.createElement("hoge")).apendChild(xml.createTextNode("ほげ?"));
xmlhttp.open("POST", "/script/ajax2.cgi" , true);
xmlhttp.send(xml);
ajax/xmlhttprequest/sample.1187887146.txt.gz · 最終更新: 2007/08/23 16:39 by 127.0.0.1