0


JavaWeb——AJAX(附三级联动省、市、区案例)

目录

1. 定义

AJAX:异步的JavaScript和xml,并不是新的编程,指的是一种交互方式,异步加载,客户端和服务器的数据交互更新在局部页面的技术,不需要刷新整个页面(局部刷新)

1.1 优点

  • 局部刷新,效果更好
  • 用户体验更好

2. 基于jQuery的AJAX

2.1 语法

$.ajax({属性})

常用的属性参数:

  • url:请求的后端服务地址
  • type:请求类型,默认get
  • data:请求参数
  • dataType:服务器返回的数据类型,text/json
  • success:请求成功的回调函数
  • error:请求失败的回调函数
  • complete:请求完成的回调函数(无论成功或者失败,都会回调)

2.2 JSON

一种轻量级数据交互格式,完成js和java等后端开发语言对象数据之间的转换
客户端和服务器之间传递对象数据,需要用JSON格式

var user ={
    id:1,
    name:"张三",
    score:96.5}

相当于java中的

packageentity;publicclassUser{privateInteger id;privateString name;privateDouble score;publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetName(){return name;}publicvoidsetName(String name){this.name = name;}publicDoublegetScore(){return score;}publicvoidsetScore(Double score){this.score = score;}publicUser(Integer id,String name,Double score){super();this.id = id;this.name = name;this.score = score;}}User user =newUser(1,"张三",96.5);

将java对象转为json格式

User user =newUser(1,"张三",96.0);//将java对象转为json格式
        resp.setCharacterEncoding("utf-8");JSONObject jsonObject =JSONObject.fromObject(user);
        resp.getWriter().write(jsonObject.toString());

2.3 案例

jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Insert title here</title><scripttype="text/javascript"src="js/jquery-3.0.0.min.js"></script><scripttype="text/javascript">/* $(function(){
    alert(123)
}) */$(function(){var btn =$("#btn");
        btn.click(function(){//alert("点击了按钮")
            $.ajax({//相当于<form action="">
                url:'testservlet',
                type:'get',
                data:'id=1',
                dataType:'text',success:function(data){//alert(data)var text =$("#text");
                    text.before("<span>"+data+"</span><br>");}});});})</script></head><body><inputid= texttype="text"><br><inputid="btn"type="button"value="提交"><br></body></html>

注1: 不能用表单提交请求,改用jQuery方式动态绑定时间来提交。
注2: servlet不能直接跳转到jsp,只能将数据返回。

//alert(data)

调用这条注释语句,即可看到结果,就是原因。

servlet

packagebysj01;importjava.io.IOException;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;@WebServlet("/testservlet")publicclassTestServletextendsHttpServlet{@OverrideprotectedvoiddoGet(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{String id = req.getParameter("id");try{Thread.sleep(30);}catch(InterruptedException e){// TODO Auto-generated catch block
            e.printStackTrace();}String str ="Hello World";
        resp.getWriter().write(str);//        req.setAttribute("str", str);//        req.getRequestDispatcher("test.jsp").forward(req, resp);}}

3. 传统的WEB数据交互 VS AJAX数据交互

  • 客户端请求的方式不同 传统:浏览器发送同步请求<form><a> AJAX:异步引擎对象发送异步请求
  • 服务器响应的方式不同 传统:响应一个完整jsp页面(视图) AJAX:相应需要的数据
  • 客户端处理方式不同 传统:需要等待服务器完成响应并且重新加载整个页面之后,用户才能进行后续的操作 AJAX:动态更新页面中的局部内容,不影响用户的其他操作

4. AJAX原理

在这里插入图片描述

5. 三级联动案例

5.1 案例说明

分为省、市、区三个部分
在点击省的时候市、区自动更新

在这里插入图片描述
在这里插入图片描述

5.2 代码

location.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Insert title here</title><scripttype="text/javascript"src="js/jquery-3.0.0.min.js"></script><scripttype="text/javascript">$(function(){//修改省份$("#province").change(function(){var id=$(this).val();
            $.ajax({
                url:"location",
                type:"post",
                data:"id="+id+"&type=province",
                dataType:"JSON",success:function(data){
                    console.log(data);var content ="";var cities = data.cities;
                    console.log(cities);for(var i=0;i<cities.length;i++){
                        content +="<option>"+cities[i]+"</option>";}$("#city").html(content);
                    
                    content ="";var areas = data.areas;
                    console.log(areas);for(var i=0;i<areas.length;i++){
                        content +="<option>"+areas[i]+"</option>";}$("#area").html(content);}});});//修改城市$("#city").change(function(){var id =$(this).val();
            $.ajax({
                url:"location",
                type:"post",
                data:"id="+id+"&type=city",
                dataType:"JSON",success:function(data){
                    console.log(data)var content ="";for(var i=0;i<data.length;i++){
                        content +="<option>"+data[i]+"</option>";}$("#area").html(content);}});});})</script></head><body>
    省:<selectid="province"><optionvalue="陕西省">陕西省</option><optionvalue="河南省">河南省</option><optionvalue="江苏省">江苏省</option></select>
    市:<selectid="city"><optionvalue="西安市">西安市</option><optionvalue="宝鸡市">宝鸡市</option><optionvalue="渭南市">渭南市</option></select>
    区:<selectid="area"><optionvalue="雁塔区">雁塔区</option><optionvalue="莲湖区">莲湖区</option><optionvalue="新城区">新城区</option></select></body></html>

class:Location

packageentity;importjava.util.List;publicclassLocation{privateList<String> cities;privateList<String> areas;publicList<String>getCities(){return cities;}publicvoidsetCities(List<String> cities){this.cities = cities;}publicList<String>getAreas(){return areas;}publicvoidsetAreas(List<String> areas){this.areas = areas;}}

servlet:LocationServlet

packageservlet;importjava.io.IOException;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importnet.sf.json.JSONArray;importnet.sf.json.JSONObject;importentity.Location;@WebServlet("/location")publicclassLocationServletextendsHttpServlet{privatestaticMap<String,List<String>> cityMap;privatestaticMap<String,List<String>> provinceMap;static{
        cityMap =newHashMap<>();List<String> areas =newArrayList<>();//陕西省//西安
        areas.add("雁塔区");
        areas.add("莲湖区");
        areas.add("新城区");
        cityMap.put("西安市", areas);//宝鸡
        areas =newArrayList<>();
        areas.add("陈仓区");
        areas.add("渭宾区");
        areas.add("新城区");
        cityMap.put("宝鸡市", areas);//渭南
        areas =newArrayList<>();
        areas.add("临渭区");
        areas.add("高新区");
        cityMap.put("渭南市", areas);//河南省//郑州
        areas =newArrayList<>();
        areas.add("郑州A区");
        areas.add("郑州B区");
        cityMap.put("郑州市", areas);//洛阳
        areas =newArrayList<>();
        areas.add("洛阳A区");
        areas.add("洛阳B区");
        cityMap.put("洛阳市", areas);//江苏省//南京
        areas =newArrayList<>();
        areas.add("南京A区");
        areas.add("南京B区");
        cityMap.put("南京市", areas);//苏州
        areas =newArrayList<>();
        areas.add("苏州A区");
        areas.add("苏州B区");
        cityMap.put("苏州市", areas);//南通
        areas =newArrayList<>();
        areas.add("南通A区");
        areas.add("南通B区");
        cityMap.put("南通市", areas);
        
        provinceMap=newHashMap<>();List<String> cities =newArrayList<>();
        cities.add("西安市");
        cities.add("宝鸡市");
        cities.add("渭南市");
        provinceMap.put("陕西省", cities);
        cities =newArrayList<>();
        cities.add("郑州市");
        cities.add("洛阳市");
        cities.add("开封市");
        provinceMap.put("河南省", cities);
        cities =newArrayList<>();
        cities.add("南京市");
        cities.add("苏州市");
        cities.add("南通市");
        provinceMap.put("江苏省", cities);}@OverrideprotectedvoiddoPost(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{String type = req.getParameter("type");
        resp.setCharacterEncoding("utf-8");String id = req.getParameter("id");switch(type){case"city":List<String> areas = cityMap.get(id);JSONArray jsonArray =JSONArray.fromObject(areas);
            resp.getWriter().write(jsonArray.toString());break;case"province":List<String> cities = provinceMap.get(id);String city = cities.get(0);List<String> cityAreas = cityMap.get(city);Location location =newLocation();
            location.setCities(cities);
            location.setAreas(cityAreas);JSONObject jsonObject =JSONObject.fromObject(location);
            resp.getWriter().write(jsonObject.toString());break;}}}
标签: ajax javascript java

本文转载自: https://blog.csdn.net/weixin_43820008/article/details/122778658
版权归原作者 weixin_43820008 所有, 如有侵权,请联系我们删除。

“JavaWeb&mdash;&mdash;AJAX(附三级联动省、市、区案例)”的评论:

还没有评论