xmlhttp是一种方法,如果不想用的话,还可以在jsp里面直接把所有的省和市先查找出来,然后通过switch把它们一一对应起来,然后在循环生成select,下面是一个小例子。

解决方案 »

  1.   

    用js就好了,这方面的代码网上很多。原理是动态生成js,大致是用两个数组,然后关联,onchange的时候把市改一下。
      

  2.   

    将省的值放到iFrame中,然后提交iframe中的form到servlet,查出值后再动态的写iframe,在iframe中使用js更新市的选项
    这样主页面就不需要刷新也能实现关联
      

  3.   

    在onchange属性上调用changeCity()方法
    function changeCity(){
      t = document.form1.selectProvince;//区局ID
      n1 = document.form1.selectCity;//辖区ID
      update_city(t.options[t.options.selectedIndex].value, n1);
      return ;
    }
    function update_city(CatID1, stationF){
    stationF.length=1;
    switch ( CatID1 ){
      <%
          //遍历所有省的集合
          ArrayList provinceCol= *; (provinceCol为所有省的集合)
          ArrayList cityCol = *; (cityCol为所有市的集合)      int count = 1;
          if(provinceCol!=null&&provinceCol.size()>0){
              Iterator it = provinceCol.iterator();
              while(it.hasNext()){
                  ProvinceVO pvo = (ProvinceVO)it.next();
      %>
            case "<%=pvo.getProvinceId%>":
                <%
                  //遍历所有市的集合
                  count = 1;
                  if (cityCol!=null&&cityCol.size()>0) {
                      Iterator it2 = cityCol.iterator();
                      while(it2.hasNext()){
                          CityVO cvo = (CityVO)it2.next();
                          if ((pvo.getProvinceId).equals(cvo.getProvinceId)) {
                              String cityName = cvo.getCityName();
                              String cityId = cvo.getCityId();
                %>
                           stationF.options[<%=count++%>]=new Option("<%=cityName %>","<%=cityId %>");
                     <%
                          }
                      }
                  }
                  %>
            break;
            <%
              }
          }
          %>
    }
    return -1;
    }大致代码是这样的,可能还需要实际调试一下,如果有什么问题,欢迎提出讨论.
    这种方法适用与关联不是很多的情况,如果是很多个select关联在一起,建议用xmlhttp来实现
      

  4.   

    给你个例子看一下:
    <script language="JavaScript">
    var city = new Array();
    <%
    int city=0;
    Vector city_v = Common.getCityDict("BornPlaceCode");
    Hashtable city_h = null;
    Enumeration city_e = city_v.elements();
    while(city_e.hasMoreElements()) {
      city_h=(Hashtable)city_e.nextElement();
    %>
    city[<%=city%>]=new Array('<%=city_h.get("parent")%>','<%=city_h.get("name")%>','<%=city_h.get("code")%>');
    <%
    city+=1;
    }
    %>
    function changeselect(BornPlaceCode){
            document.EM2Form1.BornPlaceCode.length = 0;
            document.EM2Form1.BornPlaceCode.options[0] = new Option('','');
            for (i=0; i<city.length; i++)
            {
                    if (city[i][0] == BornPlaceCode)
                    {
                      document.EM2Form1.BornPlaceCode.options[document.EM2Form1.BornPlaceCode.length] = new Option(city[i][1], city[i][2]);
                      if(city[i][2]=="<%=BornPlaceCode%>"){
                       document.EM2Form1.BornPlaceCode.options[document.EM2Form1.BornPlaceCode.length].selected=true;
                      }
                  }
            }
    }
      

  5.   

    function showCity()   
      {
       var province_id = document.form1.Province_id.value
       if(province_id == "")
         return false   var Str = new Array()
       var selectStr   <%  while(province_rs.next()) {  %>  
       selectStr = ' <% key.setSqlString("select * from province where Parent_id = "+province_rs.getInt("Id")); city_rs = key.executeQuery(); %>'
       Str[<%=province_rs.getInt("Id")%>]= " <select name='City_id'><option value=''>------------------------</option><% while(city_rs.next()) { %><option value='<%=city_rs.getInt("Id")%>'><%=city_rs.getString("Name")%></option><% } %></select>"
       <% city_rs.close(); }  %> 
       if(province_id == 0) 
          window.city.innerHTML = "<select name='City_id'><option value=''>----------------------</option></select>"
       else
          window.city.innerHTML = Str[province_id]
      
       return true      
      }
      

  6.   

    上面的的是一种效果,还有一种效果:
    <script language="JavaScript">
    var citycount; 
    var city = new Array(); 
    <%
    int i=0;
    while(rs.next()){
      key.setSqlString("select * from province where Parent_id = "+rs.getInt("Id")); 
      city_rs = key.executeQuery();
      while(city_rs.next()){ 
     %> 
      
      city[<%=i%>] = new Array("<%=city_rs.getInt("Id")%>","<%=city_rs.getString("Name")%>","<%=rs.getString("Id")%>"); //定义数组

     <%
         i++;
         }//while(city_rs)
       }//while(rs)
     %>
     
    count=<%=i%>

    function showCity(Province_id){ 
    document.hotel.City_id.length = 0; 
    var j; 
    document.hotel.City_id.options[0] = new Option('=======城市========','0');
    document.hotel.City_id.options[0].selected=true; 
    for (j=0;j <count; j++){ 
    if (city[j][2] == Province_id){ 

       document.hotel.City_id.options[document.hotel.City_id.length] = new Option(city[j][1],city[j][0]); 
      }//if
      
       } //for
       
    if(document.hotel.Province_id.options[document.hotel.Province_id.selectedIndex].index>0){
       document.hotel.City_id.options[1].selected=false;
      }//if

    </script>都运行过的!
      

  7.   

    用<iFrame>与javascript技术结合很简单,把你选择的省的代码传到<iFrame>中,然后在<iFrame>中把下辖的市取出来,在<iFrame>存在一个javascript数组中,然后在页面中调用既可。
      

  8.   

    如果是jsp+javascript是必须用到数组定义的,jsp是服务器端运行的,javascript是在客服端运行的,等你把客服端的结果传过来,服务器端的jsp早运行了,你怎么根据结果查询啊?
      

  9.   

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>无标题文档</title>
    </head>
    <script language="JavaScript">
    function goSelCheJian(){
      document.form3.action="selCheJian.htm"
      document.form3.submit()
    }
    //搜索时,最大的时间默认为当前时间function showSel(){
    alert("dfdf")
    }</script>
    <body>
    <form name="form3" action="cheJian.htm" method="post">
      <table border="0"><tr><td>
    </td>
    <td>
    搜索:<select name="sel" onchange="showSel()">
      <option value="selAll">所有</option>
      <option value="selDate">日期</option>
      <option value="selMember">采购员</option>
      <option value="selMoney">价格</option>
      <option value="selWare">商品名</option>
      <option value="selType">类型</option>
    </select>
    </td>
    <td><div id="myid"></div>
    </td>
    </tr>
    </table>
    <input type="button" value="dfdf" onclick="showSel()">
    </form>
    </body>
    </html>
    <!--保存为a.html 试一下,是根据id变换<div></div>的值---->
      

  10.   

    <!---对不起上面错了--->
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <title>无标题文档</title>
    </head>
    <script language="JavaScript">
    function goSelCheJian(){
      document.form3.action="selCheJian.jsp?curPage=1"
      document.form3.submit()
    }
    //搜索时,最大的时间默认为当前时间function showSel(){
    if(document.form3.sel.value=="selAll")
       document.location="cheJian.jsp"
    if(document.form3.sel.value=="selDate")
       document.all.item('myid').outerHTML="<div id='myid'>起始日期:<input type=text name=selDate1 id=selDate1 size=20 ><img align=absMiddle alt=选择日期 height=16 id=daysOfMonthPos name=daysOfMonthPos onMouseUp=javascript:toggleDatePicker('selDate1Div','form3.selDate1') src=../public/clock.gif style=CURSOR: hand width=16><div id=selDate1Div style='POSITION: absolute'></div>&nbsp;终止日期:<input type=text name=selDate2 id=selDate2 size=20 ><img align=absMiddle alt=选择日期 height=16 id=daysOfMonthPos name=daysOfMonthPos onMouseUp=javascript:toggleDatePicker('selDate2Div','form3.selDate2') src=../public/clock.gif style=CURSOR: hand width=16><div id=selDate2Div style='POSITION: absolute'></div>&nbsp;<input type=button value='搜索' onclick='goSelCheJian()'></div>"
    if(document.form3.sel.value=="selMember")
       document.all.item('myid').outerHTML="<div id='myid'>采购员:<input type='text' name='selMember' size=10 >&nbsp;<input type=button value='搜索' onclick='goSelCheJian()'></div>"
      if(document.form3.sel.value=="selMoney")
         document.all.item('myid').outerHTML="<div id='myid'>次购买不小于:<input type='text' name='selMoney1' size=20 >元&nbsp;次购买不大于:<input type='text' name='selMoney2' size=20 >元&nbsp;<input type=button value='搜索' onclick='goSelCheJian()'></div>"
      if(document.form3.sel.value=="selWare")
         document.all.item('myid').outerHTML="<div id='myid'>商品名:<input type='text' name='selWare' size=10 >&nbsp;<input type=button value='搜索' onclick='goSelCheJian()'></div>"
      if(document.form3.sel.value=="selType")
         document.all.item('myid').outerHTML="<div id='myid'>类型:<input type='text' name='selType' size=10 >&nbsp;<input type=button value='搜索' onclick='goSelCheJian()'></div>"
    }</script>
    <body></body>
    </html>
      

  11.   

    我决定用xmlhttp做了,找了一份asp的代码,我正在改成jsp的,贴出来,大家帮忙看看改改。while(rs.next())
    {
        //遍历所有适合的数据放入arrResult数组中.
        arrResult[arrResult.length] = rs.getString("city");
        rs.MoveNext();
    }
    //escape解决了XMLHTTP。中文处理的问题.
    //数组组合成字符串.由","字符串连接.
       Response.Write(escape(arrResult.join(",")));只要把上面的asp改成jsp即可。关键的就是join方法提示没有。整个ASP源码请参照:http://dev.csdn.net/article/28/28324.shtm希望能够有人帮助我把它改成jsp版本的,以免除这一级联问题的长期困扰。谢谢!
      

  12.   

    用xmlhttp你也还是要做一个jsp或者一个action来执行根据省id来查找对应城市的方法呀。
    xmlhttp的用法如下:javascript 中的方法://onchange里调用的方法
    function changeCity(){
      var provinceId = document.form1.selectProvince.value; //获得所选的省的id
      var url = ****/GetCity.jsp?provinceId ="+provinceId ;  //把省id传到方法中,根据省id来取得城市的集合(我这里是直接做了一个jsp,在里面来查询,下面会把这个jsp给贴出来).
      var xmlhttp = null;  xmlhttp = new ActiveXObject(getXmlHttpPrefix()+".XMLHTTP");
      xmlhttp.open("GET", url, false);
      xmlhttp.send();  returnHtml=xmlhttp.ResponseText;
      document.getElementById("cityDiv").innerHTML = returnHtml;
    }
    //此方法用来获得合适的xml插件
    function getXmlHttpPrefix() {
    if (getXmlHttpPrefix.prefix)
    return getXmlHttpPrefix.prefix; var prefixes = ["Microsoft", "MSXML", "MSXML2", "MSXML3"];
    var o;
    for (var i = 0; i < prefixes.length; i++) {
    try {
    // try to create the objects
    o = new ActiveXObject(prefixes[i] + ".XmlHttp");
    return getXmlHttpPrefix.prefix = prefixes[i];
    }
    catch (ex) {};
    } throw new Error("Could not find an installed XML parser");
    }
      

  13.   

    谢谢楼上的,麻烦接着把jsp贴出来,正需要。我现在有点明白了。
      

  14.   

    changeCity()方法中,url属性调用的jsp的代码如下所示,主要就是根据省id来从后台数据库中获得相应的城市集合,然后动态的生成html脚本,用out.println()打印到前面那个xmlhttp中。通过xmlhttp.responsetext来获得html脚本,然后把这个脚本插到jsp中设置的<div id="cityDiv"></div>即可。这个方法都是在实际中使用并通过了的,没有问题。
      

  15.   

    jsp中的java代码如下:
    <%
      String CONTENT_TYPE = "text/xml;charset=GBK";
      response.setContentType(CONTENT_TYPE);  response.setHeader("Cache-Control","no-store"); //HTTP 1.1
      response.setHeader("Pragma","no-cache");        //HTTP 1.0
      response.setDateHeader ("Expires", 0);          //防止被proxy server cache  //这里是我自己做的后台持久层,直接实例化就可以用了,你可以根据你自己的具体情况来改写
      CityInfoJB cjb = new CityInfoJB ();
      CityInfoVO cvo = new CityInfoVO ();  Collection cityCol = new ArrayList();  String provinceId = request.getParameter("cscId");
      String cityName = "";
      String cityId = "";  StringBuffer strHtml = new StringBuffer();  if (provinceId != null && provinceId .length() > 0)
      {
        cityCol= cjb.getCityByProvinceId(provinceId );    if (cityCol!= null && cityCol.size() > 0)
        {
          Iterator it = cityCol.iterator();      if (it.hasNext())
          {
            strHtml.append(
            "<select name='cityId' onchange='(此处可以做二级联动)'>");
            while (it.hasNext())
            {
              cvo = (CityInfoVO) it.next();
              strHtml.append("<option value='");
              strHtml.append(cvo.getCity_id());
              if ( (!"".equals(cityId))&&cvo.getCity_id().equalsIgnoreCase(cityId)) //如果cityId有初试值
                strHtml.append("' selected>");
              else
                strHtml.append("'>");
              strHtml.append(cvo.getCity_name());
              strHtml.append("</option>");
            }
            strHtml.append("</select>");
          }
        }
        else
        {
          strHtml.append("<select name='cityId'> ");
          strHtml.append("<option value=''>");
          strHtml.append("无对应城市");
          strHtml.append("</option>");
          strHtml.append("</select>");
        }
      }else{
        strHtml.append("<select name='cityId'> ");
        strHtml.append("<option value=''>");
        strHtml.append("无对应城市");
        strHtml.append("</option>");
        strHtml.append("</select>");
      }
      out.println(strHtml.toString());%>
      

  16.   

    嘿嘿,楼主,你搞定了记得给俺多点分分哦,我可是第一次这么详细的答复别人的帖子,不要打击俺的积极性哟.....
    我说的已经够清楚了呢,你要是再搞不定,干脆提供几个接口给我调用,我帮你把页面给写出来,你直接在那个被调用的jsp里面,import进那几个方法,就行了。
      

  17.   

    放心吧,一定给你最多,我看看先,如果OK,争取尽快揭帖。还有楼上的,你去
    http://community.csdn.net/Expert/topic/3765/3765064.xml?temp=.8633539
    报个到,那里也有一点分^_^
      

  18.   

    请教iceman19821982(晨)   CityInfoJB cjb = new CityInfoJB ();
      CityInfoVO cvo = new CityInfoVO ();这两个方法应该给我class文件吧?还有
      String provinceId = request.getParameter("cscId");“cscId”在那里声明的?不好意思,麻烦给解释一下。
      

  19.   

    哎呀,不好意思,不是cscid,而是provinceid,就是从changecity()方法里传来的那个省的id。另外cityinfojb和cityinfovo方法是后台写的,用来根据省id来查询与它对应的城市信息,具体实现你可以自己到后台去写呀,应该不是很难吧。
      

  20.   

    我试试。谢谢。
    能具体说一下 cityinfojb和cityinfovo的用途吗?他们的作用应该不一样的。
      

  21.   

    是啊,我们是采用mvc架构来做的的,vo就是对数据库中相应表的一个映射,jb就是javabean呀,具体的查询数据库的方法都写在里面。当control层要对后台数据库进行操作的时候,直接调用javabean里的方法就行了。当然,具体对数据库的操作,我们用了dao模式。
    如果你要是觉得麻烦,就直接写一个java方法,通过provinceid查出对应的城市的resultset,然后用rs来做循环就可以了,只是那样做的看起来有点别扭罢了:)
      

  22.   

    其实也不用,打击如果需要,看看这个例子就性了
    http://www.csdn.com.cn/program/2522.htm
      

  23.   

    我觉得不用javaScript好一点.省的change事件直接提交到本页面.用取request.getParameter("省")得值,在用select 市 from yourTable 查数据库,得出市.