郵便番号JavaScript

var xmlHttp = getXmlHttpObj();

function getXmlHttpObj(){
    var xmlhttp;
    /*@cc_on
    @if (@_jscript_version >= 5)
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
            	// IE
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
    @else
        xmlhttp = false;
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
        	// Mozila系
            xmlhttp = new XMLHttpRequest();
            // 文字化け対策
            xmlhttp.overrideMimeType("text/xml"); 
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}


function searchZip(){
    var zip1 = document.getElementById('zip1').value;
    var zip2 = document.getElementById('zip2').value;

    // GETでURLにリクエストする。最後の引数をtrueにするとエラー時にも次の処理を行う
    xmlHttp.open('GET','/zipcode/searchZip.html?zip1='+escape(zip1)+'&zip2='+escape(zip2), true);
	
    // XMLHttpRequestオブジェクトの状態が変わるたびにhandleHttpResponseを呼ぶ。
    xmlHttp.onreadystatechange = handleHttpResponse;
	
    // サーバ側にリクエストを送信する。データを送信しない場合には引数をNULLにする
    xmlHttp.send(null);
	
}

function handleHttpResponse() {
    // 読み込んだデータの解析完了もしくはhttp statusが200の場合にレスポンスのXMLを解析。
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        var xmlDoc = xmlHttp.responseXML;
        if (xmlDoc.documentElement) {
            var code1    = xmlDoc.getElementsByTagName('code1').item(0).firstChild;
            var code2    = xmlDoc.getElementsByTagName('code2').item(0).firstChild;
            var address   = xmlDoc.getElementsByTagName('address').item(0).firstChild;
            if (code1    != null) document.getElementById('code1').value = code1.data;
            if (code2    != null) document.getElementById('code2').value = code2.data;
            if (address   != null) document.getElementById('address').value = address.data;
        } else {
            document.getElementById('code1').value = '';
            document.getElementById('code2').value = '';
            document.getElementById('address').value = '';
        }
    }
}