AJAX即「Asynchronous JavaScript and XML」(非同步的JavaScript與XML技術)
<html> ...(省略)
需要置入jquery.js
<script type="text/javascript" src="jquery.js"></script>
檔名:demo.html
AJAX即「Asynchronous JavaScript and XML」(非同步的JavaScript與XML技術)
<script>
$(document).ready(function() {
$('#city').change(function() {
var showarea = $('#showarea');
showarea.html('Loading...');
$.ajax({ url: 'getdata.php',
data: { code: $('#city').val() },
type: 'GET',
dataType: 'html',
success: function(data, textStatus, jqXHR) {
showarea.html(data); },
city跟showarea
是自己訂義的id
設定要將資料傳到哪個檔案
設定要傳送的變數
設定傳送的方式
設定回傳的格式(html/script/jason/xml)
回傳後要執行的事件
AJAX即「Asynchronous JavaScript and XML」(非同步的JavaScript與XML技術)
error: function() {
showarea.html('error !');
},
complete: function() {
// nothing to do
}
});
});
});
</script>
</head>
AJAX即「Asynchronous JavaScript and XML」(非同步的JavaScript與XML技術)
<body>
<h1>地區選擇</h1>
Code:<select name="city" id="city">
<option value="TP">台北市</option>
<option value="NT">新北市</option>
<option value="NT2">新北市2</option>
</select>
<div id="showarea" style="background-color:#AAAAFF;"></div>
</body>
</html>
city 跟 showarea和前面javascript有對應關係哦!
AJAX即「Asynchronous JavaScript and XML」(非同步的JavaScript與XML技術)
檔名:getdata.php
<?php
$p_code = isset($_GET['code']) ? $_GET['code'] : 'XX';
switch($p_code)
{ case 'TP' :
$a_data = array('木柵', '萬華', '信義', '大同' );
break;
case 'NT' :
$a_data = array('板橋', '三重', '永和', '新莊', '新店' );
break;
AJAX即「Asynchronous JavaScript and XML」(非同步的JavaScript與XML技術)
檔名:getdata.php
default:
$a_data = array('xxx', 'yyy', 'zzz'); }
$str = '';
$str .= '<SELECT size="6">';
foreach($a_data as $one)
{ $str .= '<OPTION>' . $one . '</OPTION>' . "\n"; }
$str .= '</SELECT>';
echo $str;
?>