二级菜单联动 ajax+json

来源:互联网 发布:2017淘宝恶意退款教程 编辑:程序博客网 时间:2024/04/25 11:28

 

Web应用目录:

 具体的代码如下:

AjaxJSON.java

package AjaxJson;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.List;

import net.sf.json.JSONArray;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class AjaxJSON extends HttpServlet {

 

       /**

        *

        */

       private static final long serialVersionUID = 1L;

 

       /**

        * The doGet method of the servlet. <br>

        *

        * This method is called when a form has its tag value method equals to get.

        *

        * @param request the request send by the client to the server

        * @param response the response send by the server to the client

        * @throws ServletException if an error occurred

        * @throws IOException if an error occurred

        */

       public void doGet(HttpServletRequest request, HttpServletResponse response)

                     throws ServletException, IOException {

this.doPost(request, response);

       }

 

       /**

        * The doPost method of the servlet. <br>

        *

        * This method is called when a form has its tag value method equals to post.

        *

        * @param request the request send by the client to the server

        * @param response the response send by the server to the client

        * @throws ServletException if an error occurred

        * @throws IOException if an error occurred

        */

       public void doPost(HttpServletRequest request, HttpServletResponse response)

                     throws ServletException, IOException {

 

              response.setContentType("text/html;charset=utf-8");

              String province =new String(request.getParameter("province").getBytes("ISO-8859-1"),"UTF-8") ; 

        System.out.println("后台中的参数省份是:"+province); 

        List<City> cities = new ArrayList<City>();

        JSONArray jsonArray = null; //需要带入Json-lib包;

              if ("广东省".equals(province)) {

                     City city1 = new City(1, "广州");

                     City city2 = new City(1, "深圳");

                     City city3 = new City(1, "珠海");

                     City city4 = new City(1, "佛山");

                     cities.add(city1);

                     cities.add(city2);

                     cities.add(city3);

                     cities.add(city4);

                     //java对象转换为json字符串

                     jsonArray = JSONArray.fromObject(cities);

              }

 

 

              if("海南省".equals(province))

              {

                     City city1 = new City(1, "海口");

                     City city2 = new City(1, "三亚");

                     cities.add(city1);

                     cities.add(city2);

                     jsonArray = JSONArray.fromObject(cities);

              }

             

              PrintWriter pw = response.getWriter();

              pw.write(jsonArray.toString());

              System.out.println(jsonArray.toString());

       }

 

}

 

 

 

City.java

 

package AjaxJson;

publicclass City {

  

   private Integerid;

   private Stringname

   public City(Integer id, String name) {

      super();

      this.id = id;

      this.name = name;

   }

   public Integer getId() {

      returnid;

   }

   publicvoid setId(Integer id) {

      this.id = id;

   }

   public String getName() {

      returnname;

   }

   publicvoid setName(String name) {

      this.name = name;

   }

  

  

}

 

Ajax_json.jsp

<%@ page language="java"contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

     <selectid="provinceID">

      <option>选择省份</option>

      <option>广东省</option>  

      <option>海南省</option>  

   </select>

   <selectid="cityID">

      <option>选择城市</option>

   </select>

  

  

   <scripttype="text/javascript">

 

         document.getElementById("provinceID").onchange=function()

         {

             varprovince =  this[this.selectedIndex].innerHTML;

             alert("*****************province="+province);

             varcityElement =document.getElementById("cityID");

             //删除多余的城市,从最后一个开始删除

             varsize = cityElement.options.length;

             if(size>1)

                {

             for(vari = size-1;i>0;i--)

                {

                    cityElement.removeChild(cityElement.options[i]);

                }

                }

             //加载XMLHttpRequest对象

              varxhr =  createXHR();

              xhr.onreadystatechange=function()

              {

                 if(xhr.readyState==4)

                    {

                      if(xhr.status==200)

                         {

                          //AJAX引擎读取服务端的信息

                            varxmlDocument =xhr.responseText;

                          //Java语言的String类型转换JavaScriptstring类型

                            varjson = eval(xmlDocument);

                            size= json.length;

                            for(vari = 0;i<size;i++)

                              {

                                 //得到每个城市的名称

                                   varcity = json[i].name;

                                   varoptionElement =document.createElement("option");

                                   optionElement.innerHTML=city;

                                   cityElement.appendChild(optionElement);

                              }

                            

                         }

                    }

              }

             

              varmethod = "POST";

              varsendData="province="+province;

              varurl = "${pageContext.request.contextPath}/AjaxJSON?time="+newDate().getTime();

              alert("url="+url);

              xhr.open(method,url);

              xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");

              xhr.send(sendData);

         }

      //创建XMLHttpRequest

      functioncreateXHR()

      {

         varxhr=null;

         try{

            //ie6

             xhr = newActiveXObject(microsoft.xmlhttp);

         }catch(e)

        {

            //其他浏览器

            xhr = newXMLHttpRequest();

        }

         returnxhr;

      }

 </script>

  

  

 

</body>

</html>

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 钱付了货没收到怎么办 在苏宁易购上买东西地址错了怎么办 手机分期付款银行卡丢了怎么办 华硕笔记本鼠标不动了怎么办 韵达快递不派送怎么办 中通快递不派送怎么办 农业银行信用卡密码输错三次怎么办 农业银行卡多次输错密码怎么办 想把店长弄走怎么办 济南银座卡过期了怎么办 银座购物卡丢失后怎么办 银座的卡丢了怎么办 银行卡换了旧卡怎么办 大理市民卡丢了怎么办 市民卡内的钱怎么办 宝付支付乱扣款怎么办 苏宁任性贷逾期怎么办 第二次跟家里开口要钱还网贷怎么办 网贷到家来要钱怎么办 网贷贷不了啦急要钱怎么办 百度推广竞价关键词太长怎么办 药店位置差客流少怎么办 网站上的用词违规怎么办 苹果16g内存不够怎么办 手机16g内存不够怎么办 在私企年纪大了怎么办 谷歌浏览器显示不安全打不开怎么办 4s密码多次错误怎么办 苹果4s手机系统错误怎么办 汽车充电口坏了怎么办 如果手机充不了电怎么办 淘宝买的家电坏了怎么办 衣服皱了没有熨斗怎么办 油烟机油盒坏了怎么办 实体店不给换货怎么办 台式电脑鼠标不动了怎么办 电脑开机一直长鸣报警怎么办 国外电话卡网速太慢怎么办 滴滴提现忘记登录密码怎么办 微信提现支付密码忘记了怎么办 小米手机前置摄像头打不开怎么办