说明:post方式提交,response返回类型为xml。 ajax,js见上一篇博文
showCities.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/ajax.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
function getCities() {
var url = "${pageContext.request.contextPath}/showCitiesPro.jsp";
var data = "province=" + $('province').value;
if ($('province').value != "") {
send_request("POST", url, data, "text", showFeedbackInfo);
}
}
function showFeedbackInfo() { //回调函数
if (http_request.readyState == 4) { // 判断对象状态
if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
var xmlDoc=http_request.responseXML;
var cities=xmlDoc.getElementsByTagName("city");
$('city').length=0; //每次清空下,DOM没找到删除所有节点的方法,只有删除一个节点的方法,凑合用吧
for(var i=0;i<cities.length;i++){
var cityName=cities[i].childNodes[0].nodeValue;
//创建新的元素option
var newcity=document.createElement("option");
// newcity.setAttribute("value",cityName);
newcity.value=cityName;
newcity.innerText=cityName;
$('city').appendChild(newcity);
}
} else { //页面不正常
alert("您所请求的页面有异常。。。");
}
}
}
function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<select id="province" οnchange="getCities()">
<option value="">--省--</option>
<option value="zhejiang">浙江</option>
<option value="anhui">安徽</option>
</select>
<select id="city">
<option value="">--市--</option>
</select>
<select id="county">
<option value="">--县--</option>
</select>
</body>
</html>
showCitiesPro.jsp
<%@ page contentType="text/html; charset=gb2312"%>
<%
response.setContentType("text/xml;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
String province=request.getParameter("province");
String cities="";
if(province.equals("anhui")){ //写死,可到数据库去查询,就不扩展了。数据库表建议只建一张表,通过自联来查询上一级行政单位。不用建三个表
cities="<provice><city>安庆</city><city>合肥</city><city>六安</city></provice>";
}else if(province.equals("zhejiang")){
cities="<provice><city>义乌</city><city>杭州</city><city>舟山</city></provice>";
}
out.println(cities);
%>
当一个ajax请求到服务器,服务器可以根据需求返回三种格式的数据,选那个?
1、 项目经理无特殊要求,建议用json
2、 若应用程序不需要与其他应用程序共享数据时,使用html片段来返回数据。
3、 如果数据需要重用,json比较好,在性能和文件大小有优势
4、当远程应用程序未知时,XML是首选,XML是web服务领域的世界语。