现在的位置: 首页 > 综合 > 正文

servlet+ajax实例:由省份选择城市

2013年08月11日 ⁄ 综合 ⁄ 共 2645字 ⁄ 字号 评论关闭

一、test.html 

<html>
<head>
<title>MyHtml.html</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">

</head>
<script type="text/javascript">
 function getResult(stateVal) {
   var url = "servlet/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])
  }
}
function test(){
//alert("test");
}
</script>
<body>
<select name="state" onChange="getResult(this.value)">
 <option value="">请选择</option>>
 <option value="zj">浙江</option>>
 <option value="zs">江苏</option>>
</select>
<select id="city"></select>
</body>
</html>
二、servlet源程序

package com.stephen.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import org.dom4j.*;

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

/**
* @author stephen
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
*/
public class SelectCityServlet extends HttpServlet {

public SelectCityServlet() {
super();
}

public void destroy() {
super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setCharacterEncoding("UTF8");
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
String state = request.getParameter("state");

Document document = DocumentHelper.createDocument();

Element root = document.addElement("state");

Element city = null;
if("zj".equals(state)){
city = root.addElement("city");
city.setText("杭州");
city = root.addElement("city");
city.setText("huzhou");
}else{
city = root.addElement("city");
city.setText("南京");
city = root.addElement("city");
city.setText("苏州");
city = root.addElement("city");
city.setText("yangzhou");
}

PrintWriter out=response.getWriter();
String s = root.asXML();

out.write(s);
out.close(); 
}

}

 

抱歉!评论已关闭.