Js 代碼:
<script type="text/javascript" language="javascript">
function getXmlHttp(){
var http_request = false;
if (window.XMLHttpRequest){
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType){
http_request.overrideMimeType('text/xml');
}
}else if (window.ActiveXObject){
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e) {
}
}
}
if (!http_request){
alert('<%=mess%>');
return false;
}
return http_request;
}
function getCity(value)
{
var ul="AjaxGetCityByProId?proId="+value;
req = getXmlHttp();
req.onreadystatechange = result1;
req.open("GET",ul,true);
req.setRequestHeader('If-Modified-Since', '0');
req.send(null);
}
function result1(){
if(req.readyState == 4 && req.status == 200)
{
var citys = req.responseText.toString();
document.getElementById("divCity").innerHTML=citys;
}
}
</script>
部分html代碼:
<TR bgColor=#AD8B4D>
<TD align=right width="97">
<bean:message key="regist.province" />
</TD>
<TD width="387" align="left">
<select name="province" id="province" style="width: 140px;" class=input
onChange="getCity(this.options[this.options.selectedIndex].value);">
<option>
<bean:message key="regist.select" />
</option>
<%
Province pr = null;
for (int i = 0; i < allPros.size(); i++) {
pr = (Province) allPros.get(i);
%>
<option value="<%=pr.getProId() %>">
<%=pr.getProName() %>
</option>
<%
}
%>
</select>
</TD>
</TR>
<TR bgColor=#AD8B4D>
<TD align=right width="97">
<bean:message key="regist.city" />
</TD>
<TD width="387" align="left">
<span id="divCity"></span>
</TD>
</TR>
部分 servlet代碼:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = request.getContextPath();
response.setContentType("text/xml; charset=GBK");
PrintWriter out = response.getWriter();
String proIds = request.getParameter("proId");
Long proId = Long.parseLong(proIds);
ServletContext application = request.getSession().getServletContext();
WebApplicationContext webContext = WebApplicationContextUtils
.getRequiredWebApplicationContext(application);
UserService users = (UserService) webContext.getBean("userService");
List allCity = null;
try {
allCity = users.getAllCityByProId(proId);
City city = null;
StringBuffer cityStr = new StringBuffer();
cityStr.append("<select name=/"city/">");
for (int i = 0; i < allCity.size(); i++) {
city = (City) allCity.get(i);
cityStr.append(" <option value='" + city.getCityId() + "'>")
.append(city.getCityName()).append("</option>");
}
cityStr.append("</select>");
out.print(cityStr);
} catch (Exception e) {
response.sendRedirect(path + "/error.jsp");
}
}