<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String basePath = request.getContextPath();
pageContext.setAttribute("basePath", basePath);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>ajax异步选择城市</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
//页面加载完毕,然后执行
window.onload=function(){
//创建异步通讯对象
var xmlhttp;
function createXMLHttpRequest(){
//判断不同的浏览器,使用不同的xml请求,固定写法
//code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp =new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
//给下拉列表一个onchange事件,使用ajax技术,往city中写入城市
document.getElementById("country").onchange=function(){
//获取国家
var country = this.value;
//创建xmlhttp对象
createXMLHttpRequest();
//设置回调函数
xmlhttp.onreadystatechange =getData;
//创建一个连接,post提交,发送数据是一定要填数据
xmlhttp.open("post", "${basePath}/ajax",true);
//设置表单类型
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//发送连接、数据,post提交,发送里面是一定要填数据
xmlhttp.send("country="+country)
}
//接收服务器返回的数据:xml格式
//同上的回调函数
function getData(){
//固定写法
if (xmlhttp.readyState==4) {
if (xmlhttp.status==200) {
//获取服务器返回的文本
var jsonStr=xmlhttp.responseText;
//eval()把字符串转换成json格式
var jsn =eval("("+jsonStr+")");
//下拉列表展示
var selCity = document.getElementById("city");
//清空下拉列表
selCity.length=0;
for (var i = 0; i< jsn.cities.length;i++) {
//获取城市
var city =jsn.cities[i].city;
//添加到city下拉列表中
var opt =document.createElement("option");
opt.text =city;
selCity.appendChild(opt);
}
}
}
}
/* json范例
var jsn = {
cities:[
{"city":"北京"},
{"city":"上海"},
{"city":"广州"},
{"city":"深圳"}
]};
在谷歌console控制台输出(ctrl+shift+I会弹出页面)
console.log( jsn.cities.length );
console.log( jsn.cities[0].city );
*/
}
</script>
</head>
<body>
<div style="width:100%;text-align: center;margin-top: 30px;">
国家:<select id="country" style="width:160px;">
<option>请选择</option>
<option value="中国">中国</option>
<option value="美国">美国</option>
</select>
---
城市:<select id="city"></select>
</div>
</body>
</html>
国家城市二级联动jsp页面
最新推荐文章于 2024-03-27 23:32:00 发布