利用js和servlet的形成下拉菜单联动

jsp:


js:

利用js和servlet的形成下拉菜单联动_第1张图片

servlet

利用js和servlet的形成下拉菜单联动_第2张图片




js代码:

      function createXmlHttpRequest() {
var xmlHttp;
try {
//firfox,opera,safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
//internet explorer
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
return xmlHttp;
}
function liandong() {
document.getElementById("jxs").innerHTML="<option>选择经销商</option>";
document.getElementById("city").innerHTML="<option>选择市</option>";
var index = document.getElementById("pro").selectedIndex;
//alert(index);
var pro = document.getElementById("pro").options[index].value;
//alert(pro);
xmlHttp = createXmlHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
//alert(xmlHttp.status);
if (xmlHttp.status == 200) {
//alert(1);
var data = xmlHttp.responseText;
//alert(data);
document.getElementById("city").innerHTML=data;


}
}
};
xmlHttp.open("post", "../check", true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send("pro="+pro);
}

2.servlet代码

package edu.cslg.huachen.servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import edu.cslg.huachen.util.ReadXml;
import edu.cslg.huachen.util.XmlObject;


@WebServlet(name = "check", urlPatterns = { "/check" })
public class Adress extends HttpServlet {
private static final long serialVersionUID = 1L;
private List<XmlObject> xmlList;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String pro = (String) request.getParameter("pro");
xmlList = new ReadXml().readXml(request);
StringBuffer buffer = new StringBuffer();
if (pro != null) {
buffer.append("<option value=''>选择市</option>");
for (int i = 0; xmlList != null && i < xmlList.size(); i++) {
XmlObject xmlObject = xmlList.get(i);
// System.out.println(xmlObject.getPro());
if (xmlObject.getPro().equals(pro)) {
buffer.append("<option value='" + xmlObject.getCity()
+ "'>" + xmlObject.getCity() + "</option>");
}
}
} else {
String city = request.getParameter("city");
buffer.append("<option value=''>选择经销商</option>");
for (int i = 0; xmlList != null && i < xmlList.size(); i++) {
XmlObject xmlObject = xmlList.get(i);
// System.out.println(xmlObject.getCity());
if (xmlObject.getCity().equals(city)) {
buffer.append("<option value='" + xmlObject.getJxs() + "'>"
+ xmlObject.getJxs() + "</option>");
}
}
}
String date = buffer.toString();
PrintWriter out = response.getWriter();
out.print(date);
}
}


你可能感兴趣的:(利用js和servlet的形成下拉菜单联动)