1.AJAX快速入门
AJAX 简介 (w3school.com.cn)https://www.w3school.com.cn/js/js_ajax_intro.asp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
//1.创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.发送请求
xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet", true);
xhttp.send();
//3.获取响应
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
}
</script>
</body>
</html>
import java.io.IOException;
@javax.servlet.annotation.WebServlet("/ajaxServlet")
public class AjaxServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request, response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//响应数据
response.getWriter().write("hello ajax");
}
}
2.案例:使用AJAX验证用户名是否存在
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="#" method="get">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名已存在</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img src="imgs/a.jpg">
<a href="#" id="changeImg">看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
//1.绑定失去焦点时间
document.getElementById("username").onblur = function () {
//2.发送ajax请求
//获取用户名
var username = this.value;
//2.1 创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.2 发送请求,携带参数
xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username=" + username);
xhttp.send();
//2.3 获取响应
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText == "true") {
//用户名存在,显示提示信息
document.getElementById("username_err").style.display = "";
} else {
//用户名不存在,隐藏提示信息
document.getElementById("username_err").style.display = "none";
}
}
}
}
</script>
</body>
</html>
@WebServlet("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受用户名
String username = request.getParameter("username");
//2.调用service查询用户名是否存在(此处模拟查询结果)
boolean flag = true;
//3.响应标记
response.getWriter().write("" + flag);
}
}
3.Axios异步框架
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="js/axios-0.18.0.js"></script>
<script>
//1.get
axios({
method: "get",
url: "http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
//2.post
axios({
method: "post",
url: "http://localhost:8080/ajax-demo/axiosServlet",
data:"username=lisi"
}).then(function (resp) {
alert(resp.data);
})
</script>
</body>
</html>
@WebServlet("/axiosServlet")
public class AxiosServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//1.获取请求参数
String username = request.getParameter("username");
//2.响应数据
response.getWriter().write("hello " + username + "!");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="js/axios-0.18.0.js"></script>
<script>
// //1.get
// axios({
// method: "get",
// url: "http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
// }).then(function (resp) {
// alert(resp.data);
// })
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
alert(resp.data);
})
//
// //2.post
// axios({
// method: "post",
// url: "http://localhost:8080/ajax-demo/axiosServlet",
// data:"username=lisi"
// }).then(function (resp) {
// alert(resp.data);
// })
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=lisi").then(function (resp) {
alert(resp.data);
})
</script>
</body>
</html>
@WebServlet("/axiosServlet")
public class AxiosServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
//1.获取请求参数
String username = request.getParameter("username");
//2.响应数据
response.getWriter().write("hello " + username + "!");
}
}
案例:失焦显示“用户名已存在”
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="#" method="get">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名已存在</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img src="imgs/a.jpg">
<a href="#" id="changeImg">看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script src="js/axios-0.18.0.js"></script>
<script>
//1.绑定失去焦点时间
document.getElementById("username").onblur = function () {
axios({
method: "get",
url:"http://localhost:8080/ajax-demo/selectUserServlet?username=zhangsan"
}).then(function (resp) {
if (resp.data = "true") {
//!!!!!!!!!!!注意是用=表示判断!!!!!!!!!!!!
//用户名存在,显示提示信息
document.getElementById("username_err").style.display = "";
} else {
//用户名不存在,隐藏提示信息
document.getElementById("username_err").style.display = "none";
}
})
}
</script>
</body>
</html>
@WebServlet("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受用户名
String username = request.getParameter("username");
//2.调用service查询用户名是否存在(此处模拟查询结果)
boolean flag = true;
//3.响应标记
response.getWriter().write("" + flag);
}
}
4.JSON
JSON基础语法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var json={
"name":"zhangsan",
"age":23,
"addr":["北京","上海","广州"]
}
alert(json.name)
</script>
</body>
</html>
?
JSON数据和Java对象转换
?
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
public class FastJsonDemo {
public static void main(String[] args) {
//1.java对象转json字符串
User user = new User();
user.setID(1);
user.setUsername("zhangsan");
user.setPassword("123");
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString);//{"iD":1,"password":"123","username":"zhangsan"}
//2.json字符串转java对象
User u = JSON.parseObject(jsonString, User.class);
System.out.println(u);//User{ID=1, username='zhangsan', password='123'}
}
}
5.Axios + JSON案例:完成品牌列表数据查询和添加
?
?
?
brand.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="addBrand.html"><input type="button" value="新增"></a><br>
<hr>
<table id="brandTable" border="1" cellspacing="0" width="100%"></table>
<script src="js/axios-0.18.0.js"></script>
<script>
//1.当前页面加载完成后,发送ajax请求
window.onload = function () {
//2.发送ajax请求
axios({
method: "get",
url: "http://localhost:8080/brand-demo/selelcrAllServlet"
}).then(function (resp) {
//获取数据
let brands = resp.data;
let tableData = " <tr>\n" +
" <th>序号</th>\n" +
" <th>品牌名称</th>\n" +
" <th>企业名称</th>\n" +
" <th>排序</th>\n" +
" <th>品牌介绍</th>\n" +
" <th>状态</th>\n" +
" <th>操作</th>\n" +
" </tr>";//表头
for (let i = 0; i < brands.length; i++) {
let brand = brands[i];
tableData += " <tr align=\"center\">\n" +
" <td>" + (i + 1) + "</td>\n" +
" <td>" + brand.brandName + "</td>\n" +
" <td>" + brand.companyName + "</td>\n" +
" <td>" + brand.ordered + "</td>\n" +
" <td>" + brand.description + "</td>\n" +
" <td>" + brand.status + "</td>\n" +
" <td><a href=\"#\">修改</a> <a href=\"#\">删除</a></td>\n" +
" </tr>"
}
//设置表格数据
document.getElementById("brandTable").innerHTML = tableData;
})
}
</script>
</body>
</html>
addBrand.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加品牌</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="" method="post">
品牌名称:<input id="brandName" name="brandName"><br>
企业名称:<input id="companyName" name="companyName"><br>
排序:<input id="ordered" name="ordered"><br>
描述信息:<textarea rows="5" cols="20" id="description" name="description"></textarea><br>
状态:
<input type="radio" name="status" value="0">禁用
<input type="radio" name="status" value="1">启用<br>
<input type="button" id="btn" value="提交">
</form>
<script src="js/axios-0.18.0.js"></script>
<script>
//1.绑定单击事件
document.getElementById("btn").onclick = function () {
//2.表单数据转json
//2.1定义json对象
var formData = {
"brandName": "",
"companyName": "",
"ordered": "",
"description": "",
"status": ""
};
//2.2获取并设置表单数据
let brandName = document.getElementById("brandName").value;
let companyName = document.getElementById("companyName").value;
let ordered = document.getElementById("ordered").value;
let description = document.getElementById("description").value;
formData.brandName = brandName;
formData.companyName = companyName;
formData.ordered = ordered;
formData.description = description;
let status = document.getElementsByName("status");
for (let i = 0; i < status.length; i++) {
if (status[i].checked) {
formData.status = status[i].value;
}
}
console.log(formData);
axios({
method: "post",
url: "http://localhost:8080/brand-demo/addServlet",
data: formData
}).then(function (resp) {
if (resp.data = "success") {
location.href = "http://localhost:8080/brand-demo/brand.html"
}
})
}
</script>
</body>
</html>
SelectAllServlet
@WebServlet("/selelcrAllServlet")
public class SelelcrAllServlet extends HttpServlet {
private BrandService brandService = new BrandService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.调用service查询
List<Brand> brands = brandService.selectAll();
//2.封装成json字符串
String jsonString = JSON.toJSONString(brands);
//3.发送数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
}
AddServlet
@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {
private BrandService brandService = new BrandService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受request请求体
BufferedReader reader = request.getReader();
String s = reader.readLine();
//2.把请求体转对象
Brand brand = JSON.parseObject(s, Brand.class);
//3.调用service添加
brandService.add(brand);
//4.响应标识
response.getWriter().write("success");
}
}
|