程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> php AJAX實例根據郵編自動完成地址信息

php AJAX實例根據郵編自動完成地址信息

編輯:關於PHP編程

<script>
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq(zip) {
http.open('get', 'zipcode.PHP?zip='+zip);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById("city").value = update[0];
document.getElementById("state").value = update[1];
}
}
}
</script>
<h3>Enter A United States Zipcode, Then Tab</h3>
<table align="center">
<tr>
<td>Enter Zipcode:</td>
<td><input type="text" id="zipcode" name="zipcode" onBlur="sndReq(this.value);"/></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" id="city" name="city"/></td>
</tr>
<tr>
<td>State:</td>
<td><input type="text" id="state" name="state"/></td>
</tr>
</table>
以上是客戶輸入頁面,下面是服務端的處理頁面'zipcode.PHP
<?PHP
$dbuser = 'root';
$dbpass = '111111';
$cn = mysql_connect("localhost", $dbuser, $dbpass);
$db = mysql_select_db("ajax");
$sql = "select city, state from zipcodes where zipcode = " . $_REQUEST['zip'];
$rs = mysql_query($sql);
$row = mysql_fetch_array($rs);
echo $row['city'] . "|" . $row['state'];
mysql_close($cn);
?>
當客戶輸入一個POSTCODE後,zipcode.PHP就接收到它,然後進行從數據表中取出對應的資料,再按一定的格式返回給客戶端(此處是以 | 分隔)。最後客戶端接收返回的資料,顯示在頁面上。
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById("city").value = update[0];
document.getElementById("state").value = update[1]; 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved