AJAX = Asynchronous + Javascript + xml
。简直TMD是艺术
demo.html
<html>
<head>
<title>Ajax下拉列表</title>
<meta charset="utf-8"/>
<script>
function getXhr() {
var xhr = null;
if(window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}
function change(province) {
var cities = document.getElementById("cities");
var xhr = getXhr();
xhr.open("post", "getmenu.do");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState==4 && xhr.status==200) {
var cities = xhr.responseText.split(",");
var citiesNode = document.getElementById("cities");
citiesNode.innerHTML = "";
//console.log(cities);
for(var city in cities) {
var option = document.createElement("option");
option.innerHTML = cities[city];
citiesNode.appendChild(option);
}
}
};
xhr.send("province="+province);
var citiesNode = document.getElementById("cities");
}
</script>
</head>
<body>
省份:<select id="provinces" οnchange="change(this.value);">
<option value="sd">山东</option>
<option value="js">江苏</option>
<option value="hb">河北</option>
</select>
城市:<select id="cities"></select>
</body>
</html>
MenuServlet.java
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MenuServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
PrintWriter out = res.getWriter();
String province = req.getParameter("province");
if("sd".equals(province)) {
out.print("济南,青岛,泰安");
} else if("js".equals(province)) {
out.print("南京,苏州,无锡");
} else if("hb".equals(province)) {
out.print("石家庄,唐山,秦皇岛");
}
out.flush();
out.close();
}
}