ajax动态二级表单联动

前端之家收集整理的这篇文章主要介绍了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);
}

猜你在找的Ajax相关文章