ajax异步请求数据,做下拉框联动

ajax异步请求数据,做下拉框联动

 
  ajax代码和js代码:

 

var xmlhttp;
  function getData() {
       //获取省的名称
       var provinceName = $("#select1").val();
       //创建异步调用对象
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        //加载要链接的页面
     xmlhttp.Open("POST","NodeList.jsp?query=query&name=" +encodeURI(provinceName),true);
       //将对象状态与事件相关联
       xmlhttp.onreadystatechange=statechange;
       //发送请求
       xmlhttp.Send();
    }
  function statechange() {
   $("#select2").empty(); //清除下拉框option
       //判断异步调用是否已经完成
       if(xmlhttp.readystate==4) {
         //判断完成的提示代码是否是OK状态
         if(xmlhttp.status==200) {
          if (xmlhttp.responseText!=""&&xmlhttp.responseText!=null) {
           var city = "";
           city = xmlhttp.responseText;
           var select2 = document.getElementByIdx_x("select2");
           var option= new Array(); //定义一数组
           var option2= new Array(); //定义一数组
           var option3= new Array(); //定义一数组
           option3=city.split("*"); //字符分割     
           option = option3[0].split(",");
           option2 = option3[1].split(",");
           for (var i = 0; i
            var opt=document.createElement_x("option");
            opt.value = option2[i];  //设置option的value
            opt.innerHTML=option[i]; //设置显示给用户看的值
            select2.appendChild(opt);
           }
          }

         }
       }
   }

 

java调用代码:

List r = null;
     RegionService regionService = new RegionService();
     String query = request.getParameter("query");
     if ("query".equals(query)) {
      String arr ="";

      String arr2 = "";
      String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8"); //请求编码转换
      if (!"".equals(name) && name!=null) {
        r = regionService.getRegionByName(name);
        for (int i=0; i
         arr += r.get(i).getCityName()+",";

         arr2 += r.get(i).getId()+",";

        }
      } 
      out.println(arr+"*"+arr2); //这里很重要 
      return; //返回,如果是同一个页面访问的时候
     }

 

jsp代码:

 

选择省: 
    id="select1" onchange="getData();">
     请选择省     
     

 

posted @ 2013-05-26 23:13  javawebsoa  Views(3478)  Comments(0Edit  收藏  举报