04 jquery+ajax+json

servlet
public class CityServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CityServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String country = request.getParameter("country");
        String dataType = request.getParameter("dataType");
        String sendType = request.getMethod();
        if (!"post".equals(sendType)) {
            country = new String(request.getParameter("country").getBytes("ISO-8859-1"), "utf-8");
        }
        
        StringBuffer sb = new StringBuffer("");
        if (!"json".equals(dataType)) {
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>");
            if ("中国".equals(country)) {
                sb.append("<city>北京</city>").append("<city>上海</city>").append("<city>广州</city>").append("<city>深圳</city>");
            } else if ("美国".equals(country)) {
                sb.append("<city>华盛顿特区</city>").append("<city>纽约</city>").append("<city>洛杉矶</city>").append("<city>芝加哥</city>");
            }
            sb.append("</root>");
            response.setContentType("text/xml;charset=utf-8");
        } else {
            sb.append("{");
            sb.append("\"cities\":[");
            if ("中国".equals(country)) {
                sb.append("{\"city\":\"北京\"},{\"city\":\"上海\"},{\"city\":\"广州\"},{\"city\":\"深圳\"}");
            } else if ("美国".equals(country)) {
                sb.append("{\"city\":\"华盛顿特区\"},{\"city\":\"纽约\"},{\"city\":\"洛杉矶\"},{\"city\":\"芝加哥\"}");
            }
            sb.append("]}");
            response.setContentType("text/html;charset=utf-8");
        }
        PrintWriter out = response.getWriter();
        out.println(sb.toString());
        out.flush();
        out.close();
    }
    

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
ajax_jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#country").change(function(){
                
                var country = $(this).val();//获取选中的值
                var dataType = "json"; //请求的数据格式
                if(country != undefined && country != null){
                    //根据国家获取该国的城市列表 并设置到城市下拉框中
                    $.ajax({ 
                        url:"${pageContext.request.contextPath}/CityServlet",
                        data:{"country":country,"dataType":dataType},//这里的dataType是为了让Servlet获取的
                        type:"get",
                        dataType:dataType,
                        success:function(data){
                            if("json" == dataType){
                                if(data != undefined && data != null){
                                    //将城市列表设置到城市下拉框中
                                    var cities = data.cities;
                                    //清空城市列表
                                    var $citySelect = $("#city");
                                    $citySelect.empty();
                                    
                                    $.each(cities, function(i, obj){
                                        $citySelect.append("<option>"+ obj.city +"</option>");
                                    });
                                } else { alert("操作失败。");}
                            } else {//解析xml的文本内容
                                var $xmlDocument = $(data);
                                var $cities = $xmlDocument.find("city");
                                //清空城市列表
                                var $citySelect = $("#city");
                                $citySelect.empty();
                                
                                $.each($cities, function(i, obj){//遍历所有的城市列表
                                    //设置城市下拉框中的选项
                                    $citySelect.append("<option>"+ $(obj).text() +"</option>");
                                });
                            }
                        }
                    });
                } else {
                    alert("请选择国家!");
                }
            });
        });
    </script>
<title>Insert title here</title>
</head>
<body>
    <div style="width:100%;text-align: center;margin-top: 30px;">
        国家:<select id="country" style="width:160px;">
            <option>请选择</option>
            <option value="中国">中国</option>
            <option value="美国">美国</option>
        </select>
          ---  
        城市:<select id="city"></select>
    </div>
</body>
</html>
ajax_get/post
    <script type="text/javascript">
        $(document).ready(function(){
            $("#country").change(function(){
                
                var country = $(this).val();//获取选中的值
                var dataType = "json"; //请求的数据格式
                if(country != undefined && country != null){
                    //根据国家获取该国的城市列表 并设置到城市下拉框中
                    $.get( //post
                        "${pageContext.request.contextPath}/CityServlet",
                        {"country":country,"dataType":dataType},//这里的dataType是为了让Servlet获取的
                        function(data){
                            if("json" == dataType){
                                if(data != undefined && data != null){
                                    //将城市列表设置到城市下拉框中
                                    var cities = data.cities;
                                    //清空城市列表
                                    var $citySelect = $("#city");
                                    $citySelect.empty();
                                    
                                    $.each(cities, function(i, obj){
                                        $citySelect.append("<option>"+ obj.city +"</option>");
                                    });
                                } else { alert("操作失败。");}
                            } else {//解析xml的文本内容
                                var $xmlDocument = $(data);
                                var $cities = $xmlDocument.find("city");
                                //清空城市列表
                                var $citySelect = $("#city");
                                $citySelect.empty();
                                
                                $.each($cities, function(i, obj){//遍历所有的城市列表
                                    //设置城市下拉框中的选项
                                    $citySelect.append("<option>"+ $(obj).text() +"</option>");
                                });
                            }
                        },
                        dataType//顺序不能乱哦!
                    );
                } else {
                    alert("请选择国家!");
                }
            });
        });
    </script>
getJSON
    <script type="text/javascript">
        $(document).ready(function(){
            $("#country").change(function(){
                
                var country = $(this).val();//获取选中的值
                var dataType = "json"; //请求的数据格式
                if(country != undefined && country != null){
                    //根据国家获取该国的城市列表 并设置到城市下拉框中
                    $.getJSON( //post
                        "${pageContext.request.contextPath}/CityServlet",
                        {"country":country,"dataType":dataType},//这里的dataType是为了让Servlet获取的
                        function(data){
                            if("json" == dataType){
                                if(data != undefined && data != null){
                                    //将城市列表设置到城市下拉框中
                                    var cities = data.cities;
                                    //清空城市列表
                                    var $citySelect = $("#city");
                                    $citySelect.empty();
                                    
                                    $.each(cities, function(i, obj){
                                        $citySelect.append("<option>"+ obj.city +"</option>");
                                    });
                                } else { alert("操作失败。");}
                            } else {//解析xml的文本内容
                                var $xmlDocument = $(data);
                                var $cities = $xmlDocument.find("city");
                                //清空城市列表
                                var $citySelect = $("#city");
                                $citySelect.empty();
                                
                                $.each($cities, function(i, obj){//遍历所有的城市列表
                                    //设置城市下拉框中的选项
                                    $citySelect.append("<option>"+ $(obj).text() +"</option>");
                                });
                            }
                        }
                    );
                } else {
                    alert("请选择国家!");
                }
            });
        });
    </script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文重点是来讲讲jQuery中调用ajax的4种方法:$.get、$.post、$getJSON、$ajax。内容...
    wangyujie1207阅读 1,629评论 0 9
  • 每日箴言: 每个人都有选择的权利,你不选择我,说明你选择了比我更重要的东西。[http://requirejs.o...
    全栈弄潮儿阅读 2,985评论 2 85
  • 之前在思维导图中介绍过集中请求Ajax的方法,但是只是匆匆说过,最近看了一本书,觉得介绍的比较详细,这里结合笔者自...
    范小饭_阅读 33,431评论 23 252
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,823评论 18 399
  • 20170808 夏夜,未入秋。街上人来往,塞住双耳,涌出歌声。径自文广,人影零星。 屏幕亮光,八点正。约好友,吹...
    AYRIN阅读 184评论 0 0