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

Posted 程序员超时空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaWeb——AJAX(附三级联动省市区案例)相关的知识,希望对你有一定的参考价值。

如果你是小白,这套资料可以帮你成为大牛,如果你有丰富开发经验,这套资料可以帮你突破瓶颈
2022web全套视频教程前端架构 H5 vue node 小程序 视频+资料+代码+面试题.

目录

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中的

package entity;

public class User 
	private Integer id;
	private String name;
	private Double score;
	public Integer getId() 
		return id;
	
	public void setId(Integer id) 
		this.id = id;
	
	public String getName() 
		return name;
	
	public void setName(String name) 
		this.name = name;
	
	public Double getScore() 
		return score;
	
	public void setScore(Double score) 
		this.score = score;
	
	public User(Integer id, String name, Double score) 
		super();
		this.id = id;
		this.name = name;
		this.score = score;
	
	


User user = new User(1,"张三",96.5);

将java对象转为json格式

User user = new User(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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type = "text/javascript" src = "js/jquery-3.0.0.min.js"></script>
<script type="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>
	<input id = text type = "text"><br>
	<input id = "btn" type = "button" value = "提交"><br>
</body>
</html>

注1: 不能用表单提交请求,改用jQuery方式动态绑定时间来提交。
注2: servlet不能直接跳转到jsp,只能将数据返回。//alert(data)调用这条注释语句,即可看到结果,就是原因。

servlet

package bysj01;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/testservlet")
public class TestServlet extends HttpServlet

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.0.0.min.js"></script>
<script type="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>
	省:<select id="province">
	<option value="陕西省">陕西省</option>
	<option value="河南省">河南省</option>
	<option value="江苏省">江苏省</option>
	</select>
	市:<select id="city">
	<option value="西安市">西安市</option>
	<option value="宝鸡市">宝鸡市</option>
	<option value="渭南市">渭南市</option>
	</select>
	区:<select id="area">
	<option value = "雁塔区">雁塔区</option>
	<option value = "莲湖区">莲湖区</option>
	<option value = "新城区">新城区</option>
	</select>
</body>
</html>

class:Location

package entity;

import java.util.List;

public class Location 
	private List<String> cities;
	private List<String> areas;
	public List<String> getCities() 
		return cities;
	
	public void setCities(List<String> cities) 
		this.cities = cities;
	
	public List<String> getAreas() 
		return areas;
	
	public void setAreas(List<String> areas) 
		this.areas = areas;
	
	

servlet:LocationServlet

package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import entity.Location;

@WebServlet("/location")
public class LocationServlet extends HttpServlet 
	
	private static Map<String,List<String>> cityMap;
	private static Map<String,List<String>> provinceMap;
	static 
		cityMap = new HashMap<>();
		List<String> areas = new ArrayList<>();
		//陕西省
		//西安
		areas.add("雁塔区");
		areas.add("莲湖区");
		areas.add("新城区");
		cityMap.put("西安市", areas);
		//宝鸡
		areas = new ArrayList<>();
		areas.add("陈仓区");
		areas.add("渭宾区");
		areas.add("新城区");
		cityMap.put("宝鸡市", areas);
		//渭南
		areas = new ArrayList<>();
		areas.add("临渭区");
		areas.add("高新区");
		cityMap.put("渭南市", areas);
		
		//河南省
		//郑州
		areas = new ArrayList<>();
		areas.add("郑州A区");
		areas.add("郑州B区");
		cityMap.put("郑州市", areas);
		//洛阳
		areas = new ArrayList<>();
		areas.add("洛阳A区");
		areas.add("洛阳B区");
		cityMap.put("洛阳市", areas);
		
		//江苏省
		//南京
		areas = new ArrayList<>();
		areas.add("南京A区");
		areas.add("南京B区");
		cityMap.put("南京市", areas);
		//苏州
		areas = new ArrayList<>();
		areas.add("苏州A区");
		areas.add("苏州B区");
		cityMap.put("苏州市", areas);
		//南通
		areas = new ArrayList<>();
		areas.add("南通A区");
		areas.add("南通B区");
		cityMap.put("南通市", areas);
		
		provinceMap=new HashMap<>();
		List<String> cities = new ArrayList<>();
		cities.add("西安市");
		cities.add("宝鸡市");
		cities.add("渭南市");
		provinceMap.put("陕西省", cities);
		cities = new ArrayList<>();
		cities.add("郑州市");
		cities.add("洛阳市");
		cities.add("开封市");
		provinceMap.put("河南省", cities);
		cities = new ArrayList<>();
		cities.add("南京市");
		cities.add("苏州市");
		cities.add("南通市");
		provinceMap.put("江苏省", cities);
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 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 = new Location();
			location.setCities(cities);
			location.setAreas(cityAreas);
			JSONObject jsonObject = JSONObject.fromObject(location);
			resp.getWriter().write(jsonObject.toString());
			break;
		
		
	

以上是关于JavaWeb——AJAX(附三级联动省市区案例)的主要内容,如果未能解决你的问题,请参考以下文章

三级联动怎么回显 javaweb

314 Ajax案例:邮箱地址验证,搜索框输入自动提示,省市区三级联动

ajax省市区三级联动

中国省市区地址三级联动jQuery插件 案例下载

Ajax省市区无刷新单表联动查询

使用PHP+MySql+Ajax+jQuery实现省市区三级联动功能