文章目录
一、AJAX概念与作用
二、同步与异步
三、AJAX快速入门
package cn.hncj.web;
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 java.io.IOException;
/**
* Created on 2022/3/30.
*
* @author Hou chaof
*/
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//响应数据
resp.getWriter().write("hello");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<script>
//创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//发送请求
xhttp.open("GET", "http://localhost:8080/ajaxServlet");
xhttp.send();
//获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
</script>
<body>
</body>
</html>
访问ajaxdemo1.html会弹窗显示hello
四、案例:验证用户名是否存在
package cn.hncj.web;
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 java.io.IOException;
/**
* Created on 2022/3/30.
*
* @author Hou chaof
*/
@WebServlet("servletUserServlet")
public class ServletUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收用户名
String username = req.getParameter("username");
//调用Service查询User对象
boolean flag=true;
//响应标记
resp.getWriter().write(""+flag);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
五、Axios:对原生的AJAX进行封装,简化书写
六、JSON
<!DOCTYPE html>
<html lang="zh-CN">
<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数据和Jaca对象转换
package cn.hncj.json;
import com.alibaba.fastjson.JSON;
/**
* Created on 2022/3/30.
*
* @author Hou chaof
*/
public class FastJsonDemo {
public static void main(String[] args) {
//将java对象转为JSON字符串
User user=new User();
user.setId(1);
user.setName("张三");
user.setPassword("123");
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString);
//将JSON字符串转为对象
User u = JSON.parseObject("{\"id\":1,\"name\":\"张三\",\"password\":\"123\"}", User.class);
System.out.println(u);
}
}