以下是我的JSp頁面:
<!DOCTYPE html>
<html>
<head>
<title>test1.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="../js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$("#s1").change(function(){
var pname=$("#s1").val();
if(pname!=""){
$.ajax({
url:"../deal.jsp", --------這裏的地址是你數據源的地址
type:"get",
dataType:"json",
data:"pname="+pname,
beforeSend:function(data){
$("#loading").show();
},
success:function(result){
if(typeof result!="undefined"){
$("#s2").html("");
$(result).each(function(i){
$("#s2").append("<option>"+result[i].value+"</option>");
});
};
},
complete:function(){
$("#loading").hide(2000);
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("錯誤信息"+textStatus);
}
});
}});
});
</script>
</head>
<body>
<select name="pname" id="s1">
<option value="">請選擇</option>
<option value="bj">北京市</option>
<option value="gd">廣東省</option>
<option value="hb">河北省</option>
<option value="gx">廣西省</option>
</select>
<select id="s2">
<option>請選擇</option>
</select>
<span id="loading" style="display:none">loading...</span>
</body>
</html>
以下是ajax讀取的數據源文件:
deal.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String pname = request.getParameter("pname");
String json = "";
if( pname != null ){
if ( "bj".equals(pname) ){
json = "[{\"id\":1,\"value\":\"海淀區\"},{\"id\":2,\"value\":\"豐臺區\"},{\"id\":3,\"value\":\"東城區\"},{\"id\":4,\"value\":\"房山區\"}]";
}else if( "gd".equals(pname) ){
json = "[{\"id\":1,\"value\":\"廣州市\"},{\"id\":2,\"value\":\"深圳市\"},{\"id\":3,\"value\":\"中山市\"},{\"id\":4,\"value\":\"惠州市\"}]";
}else if( "hb".equals(pname) ){
json = "[{\"id\":1,\"value\":\"長沙市\"},{\"id\":2,\"value\":\"衡州市\"},{\"id\":3,\"value\":\"株洲市\"},{\"id\":4,\"value\":\"岳陽市\"}]";
}else if( "gx".equals(pname) ){
json = "[{\"id\":1,\"value\":\"南寧市\"},{\"id\":2,\"value\":\"桂林市\"},{\"id\":3,\"value\":\"柳州市\"},{\"id\":4,\"value\":\"北海市\"}]";
}
}
out.println(json);
%>
但其實真正應該從數據庫中讀數據,我也在嘗試,如果弄好了會及時發給大家的