| Zip:<input id="zipcode" type="text" maxlength="5" onKeyUp="zipChanged()" style="width:60"/> City: <input id="city" disabled maxlength="32" style="width:160"/> State:<input id="state" disabled maxlength="2" style="width:30"/> <script src="xmlhttp.js"></script> <script> var zipField = null; function zipChanged(){ zipField = document.getElementById("zipcode") var zip = zipField.value; zip.length == 3?updateState(zip):zip.length == 5?updateCity(zip):""; } function updateState(zip) { var stateField = document.getElementById("state"); ask("resolveZip.jsp?lookupType=state&zip="+zip, stateField, zipField); } function updateCity(zip) { var cityField = document.getElementById("city"); ask("resolveZip.jsp? lookupType=city&zip="+zip, cityField, zipField); } </script> |
| HTTPRequest = function () { var xmlhttp=null; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (_e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (_E) { } } if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; } function ask(url, fieldToFill, lookupField) { var http = new HTTPRequest(); http.open("GET", url, true); http.onreadystatechange = function (){ handleHttpResponse(http, fieldToFill,lookupField)}; http.send(null); } function handleHttpResponse(http, fieldToFill, lookupField) { if (http.readyState == 4) { result = http.responseText; if ( -1 != result.search("null") ) { lookupField.style.borderColor = "red"; fieldToFill.value = ""; } else { lookupField.style.borderColor = ""; fieldToFill.value = result; } } } |
为ask()所使用的HttpRequest()函数(见上)是一跨浏览器的XMLHTTPRequest的一个实例的构造器;稍后我们将分析它。到目前为止,请注意对于handleResponse()的调用是如何用一匿名函数包装的-这个函数是function(){handleHttpResponse(http,fieldToFill, lookupField)}。