js/my.js文件代码如下:
function getXhr() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}
function $(id) {
return document.getElementById(id);
}
function $F(id) {
return $(id).value;
}
select.html文件代码如下 :
<html>
<head>
<title>select.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/my.js"></script>
<script type="text/javascript">
function getCity(v1) {
var xhr = getXhr();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
var txt = xhr.responseText;
//静安,ja;黄浦,hp;浦东新,pdx
var strs = txt.split(';');
//先清空s2
$('s2').innerHTML = '';
for (i = 0; i < strs.length; i++) {
var str1s = strs[i].split(',');
/*构造一个Option对象 */
var op = new Option(str1s[0], str1s[1]);
/* options是select的一个属性,
其值是一个数组。数组中的元素是Option对象。
*/
$('s2').options[i] = op;
}
}
};
xhr.open('get', 'getCity.do?name=' + v1, true);
xhr.send(null);
}
</script>
</head>
<body>
<!-- Ajax实现级联下拉列表 -->
<select id="s1" style="width: 120px;" onchange="getCity(this.value);">
<option value="bj">
北京
</option>
<option value="sh">
上海
</option>
<option value="gz">
广州
</option>
</select>
<select id="s2" style="width: 120px;">
</select>
</body>
</html>
ActionServlet.java文件代码如下:
package web;
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 ActionServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
// 获取请求资源路径
String uri = request.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
if (path.equals("/get_text")) {// get请求
out.println("get请求-服务器返回的数据");
} else if (path.equals("/post_text")) {// post请求
String name = request.getParameter("uname");
System.out.println(name);
out.println("又来了一次的" + name);
} else if (path.equals("/check_name")) {// 检查用户名
String name = request.getParameter("uname");
// 模拟网络延迟的操作
if (1 == 1) {
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name);
if ("Luffy".equals(name)) {
out.println("该用户名不可用");
} else {
out.println("可以使用!");
}
} else if (path.equals("/getCity")) {// 城市列表联动
String name = request.getParameter("name");
if ("bj".equals(name)) {
out.println("朝阳,cy;东城,dc");
} else if ("sh".equals(name)) {
out.println("静安,ja;黄浦,hp;浦东新,pdx");
} else {
out.println("白云,by;番禺,py");
}
}
out.close();
}
}









