客户端传统方式的请求方式(点击连接、输入网址、提交表单等)会刷新整个浏览器页面,而AJAX的优点是在不刷新整个浏览器页面的情况下向服务器发送请求
原生AJAX的使用
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function getName(){
// 获取XmlHttpRequest对象
var request = new XMLHttpRequest();
// 设置回调函数
request.onreadystatechange = function (){
if (request.readyState == 4 && request.status == 200){
// request.readyState request当前状态值,当为4时表示后端响应完成
// request.status 后端响应状态码
var i1 = document.getElementById('i1');
i1.value = request.responseText // request.responseText 后端响应的数据
}
}
// 设置请求方式和请求路径
request.open('GET','/test?name=jack');
// 发送请求
request.send();
}
</script>
</head>
<body>
<button onclick="getName()">提交</button>
<input type="text" id="i1">
</body>
</html>
后端代码:
package com.yang.servlet;
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;
@WebServlet("/test")
public class TestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("name");
resp.getWriter().write(username);
}
}
点击按钮后:
总结:利用js向后端发送请求,在不刷新整个页面的情况下获取后端响应的数据