AJAX-什么是AJAX请求
AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
ajax 是一种浏览器通过 js 异步发起请求,局部更新页面的技术。
Ajax 请求的局部更新,浏览器地址栏不会发生变化
局部更新不会舍弃原来页面的内容
AJAX-原生JavaScript的AJAX请求示例、AJAX-AJAX请求的特点说明
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//在这里使用javaScript语言发起Ajax请求,访问服务器AjaxServlet中javaScriptAjax
function ajaxRequest() {
// 1、我们首先要创建XMLHttpRequest
var xmlhttprequest = new XMLHttpRequest();
// 2、调用open方法设置请求参数
xmlhttprequest.open("GET","http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet?action=javaScriptAjax",true);
// 4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
xmlhttprequest.onreadystatechange = function () {
if (xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200) {
alert("收到服务器返回的数据:" + xmlhttprequest.responseText);
var jsonObj = JSON.parse(xmlhttprequest.responseText);
// 把响应的数据显示在页面上
document.getElementById("div01").innerHTML = "编号:" + jsonObj.id + ",姓名" + jsonObj.name;
//alert(xmlhttprequest.responseText);
}
}
// 3、调用send方法发送请求
xmlhttprequest.send();
alert("我是最后一行代码");
}
</script>
</head>
<body>
<a href="http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet?action=javaScriptAjax">非Ajax</a> <br/>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
<table border="1">
<tr>
<td>1.1</td>
<td>1.2</td>
</tr>
<tr>
<td>2.1</td>
<td>2.2</td>
</tr>
</table>
</body>
</html>
AJAX-jQuery的ajax方法、AJAX-jQuery的get和post方法、AJAX-jQuery的getJSON方法、AJAX-jQuery的serialize方法
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="script/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
// ajax请求
$("#ajaxBtn").click(function(){
$.ajax({
url:"http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet",
//data:"action=jQueryAjax",
data:{action:"jQueryAjax"},
type:"GET",
success:function (data) {
//alert("服务器返回的数据是:" + data);
//var jsonObj = JSON.parse(data);
$("#msg").html("ajax 编号:" + data.id + ",姓名:" + data.name);
},
dataType: "json"
})
//alert("ajax btn");
});
// ajax--get请求
$("#getBtn").click(function(){
$.get("http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet",
"action=jQueryGet",
function (data) {
$("#msg").html("get 编号:" + data.id + ",姓名:" + data.name);
},"json");
//alert(" get btn ");
});
// ajax--post请求
$("#postBtn").click(function(){
// post请求
$.post("http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet",
"action=jQueryPost",
function (data) {
$("#msg").html("post 编号:" + data.id + ",姓名:" + data.name);
},"json");
//alert("post btn");
});
// ajax--getJson请求
$("#getJSONBtn").click(function(){
// 调用
$.getJSON("http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet",
"action=jQueryGetJSON",
function (data) {
$("#msg").html("getJSON 编号:" + data.id + ",姓名:" + data.name);
})
//alert("getJSON btn");
});
// ajax请求
$("#submit").click(function(){
// 把参数序列化
//alert($("#form01").serialize());
$.getJSON("http://localhost:8080/JavaWeb_Code_AJAX/ajaxServlet",
"action=jQuerySerialize&" + $("#form01").serialize(),
function (data) {
$("#msg").html("Serialize 编号:" + data.id + ",姓名:" + data.name);
})
//alert("serialize()");
});
});
</script>
</head>
<body>
<div>
<button id="ajaxBtn">$.ajax请求</button>
<button id="getBtn">$.get请求</button>
<button id="postBtn">$.post请求</button>
<button id="getJSONBtn">$.getJSON请求</button>
</div>
<div id="msg">
</div>
<br/><br/>
<form id="form01" >
用户名:<input name="username" type="text" /><br/>
密码:<input name="password" type="password" /><br/>
下拉单选:<select name="single">
<option value="Single">Single</option>
<option value="Single2">Single2</option>
</select><br/>
下拉多选:
<select name="multiple" multiple="multiple">
<option selected="selected" value="Multiple">Multiple</option>
<option value="Multiple2">Multiple2</option>
<option selected="selected" value="Multiple3">Multiple3</option>
</select><br/>
复选:
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/>
单选:
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2<br/>
</form>
<button id="submit">提交--serialize()</button>
</body>
</html>
Servlet
package top.qaqaq.servlet;
import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import top.qaqaq.pojo.Person;
import java.io.IOException;
/**
* @author RichieZhang
* @create 2022-12-20 12:58
*/
public class AjaxServlet extends BaseServlet{
protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Ajax请求过来了");
Person person = new Person(1, "我");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//json 格式的字符串
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
resp.getWriter().write(personJsonString);
}
protected void jQueryAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryAjax == 方法调用了");
Person person = new Person(1, "我");
//json 格式的字符串
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
resp.getWriter().write(personJsonString);
}
protected void jQueryGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryGet == 方法调用了");
Person person = new Person(1, "我");
//json 格式的字符串
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
resp.getWriter().write(personJsonString);
}
protected void jQueryPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryPost == 方法调用了");
Person person = new Person(1, "我");
//json 格式的字符串
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
resp.getWriter().write(personJsonString);
}
protected void jQueryGetJSON(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQueryGetJSON == 方法调用了");
Person person = new Person(1, "我");
//json 格式的字符串
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
resp.getWriter().write(personJsonString);
}
protected void jQuerySerialize(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("jQuerySerialize == 方法调用了");
System.out.println("用户名:" + req.getParameter("username"));
System.out.println("密码:" + req.getParameter("password"));
Person person = new Person(1, "我");
//json 格式的字符串
Gson gson = new Gson();
String personJsonString = gson.toJson(person);
resp.getWriter().write(personJsonString);
}
}
package top.qaqaq.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* @author RichieZhang
* @create 2022-12-10 下午 12:28
*/
public abstract class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决post请求中文乱码问题
// 一定要在获取请求参数之前调用才有效
req.setCharacterEncoding("UTF-8");
// 解决响应中文乱码
resp.setContentType("text/html; charset=UTF-8");
String action = req.getParameter("action");
//方法二:通过反射动态获取
try {
// 通过action业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// System.out.println(method);
// 调用目标业务 方法
method.invoke(this,req,resp);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e); // 把异常抛给Filter过滤器
}
}
}
package top.qaqaq.pojo;
/**
* @author RichieZhang
* @create 2022-12-19 21:57
*/
public class Person {
private Integer id;
private String name;
public Person() {
}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>top.qaqaq.servlet.AjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/ajaxServlet</url-pattern>
</servlet-mapping>
</web-app>