<html>
<head>
<title>Ajax入門</title>
<style type="text/css">
<!--
body{
font-size:13px;
background-color:#e7f3ff;
}
form{
padding:0px; margin:0px;
}
input{
border-bottom:1px solid #007eff; /* 底線 */
font-family:Arial, Helvetica, sans-serif;
color:#007eff;
background:transparent;
border-top:none;
border-left:none;
border-right:none;
}
p{
margin:0px;
padding:2px 2px 2px 10px;
background:url(icon.gif) no-repeat 0px 10px; /* 加入小icon表徵圖 */
}
-->
</style>
<script language="javascript">
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
//建立XMLHttpRequest對象
createXMLHttpRequest();
function callServer(){
//擷取表單中的資料
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
//如果沒有填寫則返回
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
//連結的伺服器,自動獲得代號。本例沒有連結的伺服器,只是樣本
var url = "getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
//開啟連結
xmlHttp.open("GET", url, true);
//告訴伺服器在運行完成後(可能要用五分鐘或者五個小時)做什麼,這裡觸發updatePage函數
xmlHttp.onreadystatechange = updatePage;
//發送請求
xmlHttp.send(null);
}
//處理伺服器響應
function updatePage(){
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("zipCode").value = response;
}
}
</script>
</head>
<body>
<form>
<p>城市: <input type="text" name="city" id="city" size="25" onChange="callServer();"></p>
<p>國家: <input type="text" name="state" id="state" size="25" onChange="callServer();"></p>
<p>代號: <input type="text" name="zipCode" id="city" size="5"></p>
</form>
</body>
</html>