ajax动态二级表单联动

配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance
"

xmlns="
http://java.sun.com/xml/ns/javaee
" xmlns:web="
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
"

xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
"

id="WebApp_ID" version="2.5">

<display-name>Str</display-name>

<servlet>

<servlet-name>SelectCityServlet</servlet-name>

<servlet-class>servlet.SelectCityServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SelectCityServlet</servlet-name>

<url-pattern>/SelectCityServlet</url-pattern>

</servlet-mapping>

</web-app>

JSP文件

<body>

<select name="state" onChange=getResult(this.value)>

<option value="">Select</option>

<option value="zj">ZEHJIANG</option>

<option value="zs">JIANGSU</option>

</select>

<select id="city">

<option value="">CITY</option>

</select>

</body>
<script type="text/javascript">

function getResult(stateVal) {

//alert("1~begin");

var url = "SelectCityServlet?state=" + stateVal;

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

} else if (window.ActiveXObject) {

req = new ActiveXObject("Microsoft.XMLHTTP");

}

if (req) {

req.open("GET",url,true);

req.onreadystatechange = complete;

req.send(null);

}

}

function complete() {

if (req.readyState == 4) {

if (req.status == 200) {

var city = req.responseXML.getElementsByTagName("city");

//alert(city.length);

var str = new Array();

for ( var i = 0; i < city.length; i++) {

str[i] = city[i].firstChild.data;

}

//alert(document.getElementById("city"));

buildSelect(str,document.getElementById("city"));

}

}

}

function buildSelect(str,sel) {

sel.options.length = 0;

for ( var i = 0; i < str.length; i++) {

sel.options[sel.options.length] = new Option(str[i],str[i])

}

}

</script>

servlet:

@Override
protectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)
throwsServletException,IOException{
resp.setContentType("text/xml");
resp.setHeader("Cache-Control","no-cache");
Stringstate=req.getParameter("state");
StringBuffersb=newStringBuffer("<state>");
if("zj".equals(state)){
sb.append("<city>hangzhou</city><city>huzhou</city>");
}elseif("zs".equals(state)){
sb.append("<city>nanjing</city><city>yangzhou</city><city>suzhou</city>");
}
sb.append("</state>");
PrintWriterout=resp.getWriter();
out.write(sb.toString());
out.close();
}
@Override
protectedvoiddoPost(HttpServletRequestreq,IOException{
this.doGet(req,resp);
}

相关文章

JS原生Ajax操作(XMLHttpRequest) GET请求 POST请求 兼容性问题 利用iframe模拟ajax 实现表单提交的返回...
AJAX 每日更新前端基础,如果觉得不错,点个star吧 &#128515; https://github.com/WindrunnerMax/E...
踩坑Axios提交form表单几种格式 前后端分离的开发前后端, 前端使用的vue,后端的安全模块使用的SpringSe...
很早就听闻ajax的名声,但是却一直不知道怎么用,今天自己捣鼓了一下,竟然会用了,哈哈哈哈。 为了防止...
需要在服务器上进行哈 jquery的ajax方法: // jquery请求 $.ajax({ url: &quot;./server/slider.js...
Ajax函数封装ajax.js // Get / Post // 参数 get post // 是否异步 // 如何处理响应数据 // URL // var...