3、Ajax
AJAX(ASynchronous JavaScript And XML) 异步的JavaScript和XML, 是一种无需重新加载整个网页的情况下,能够更新部分网页的技术。
实现方式
- 原生JS实现方式(了解)
- JQuery实现方式
$.ajax()
$.get()
$.post()
JQery - $.ajax()
后端代码如下
@WebServlet("/AjaxServlet") public class AjaxServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String age = request.getParameter("age"); System.out.println("username:" + username + "--" + "age:" + age); // 休眠5秒 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } response.getWriter().write("you are ok"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
前端代码发送ajax请求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <script src="js/jquery-3.3.1.min.js"></script> <script src="js/bootstrap.min.js"></script> <script> $(function () { $("#myBtn").click(function () { var $btn = $(this).button('loading'); $.ajax({ url: "AjaxServlet", // 请求路径 type: "post", //请求方式 data: {"username": "heboan", "age": 18}, //请求参数 success: function (data) { $btn.button('reset'); console.log(data); }, //响应成功后的回调函数 error: function () { $btn.button('reset'); console.log("出错了..."); }, //表示如果请求响应出现错误,会执行的回调函数 dataType:"text"//设置接受到的响应数据的格式 }); }) }); </script> </head> <body> <button type="button" id="myBtn" data-loading-text="加载中..." class="btn btn-primary" autocomplete="off"> 发送异步请求 </button> </body> </html>
JQuery - $.get()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { $.get("ajaxServlet",{username:"rose", "age": 18},function (data) { alert(data); },"text"); } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun();"> <input> </body> </html>
JQuery - $.post()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> //定义方法 function fun() { $.post("ajaxServlet",{username:"rose", "age": 18},function (data) { alert(data); },"text"); } </script> </head> <body> <input type="button" value="发送异步请求" onclick="fun();"> <input> </body> </html>
案例 - 用户名检测
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-3.3.1.min.js"></script> <script> $(function () { // 给username绑定blur(失去焦点)事件 $("#username").blur(function () { // 获取表单值 var username = $(this).val(); /* 发送ajax请求 期望服务器响应回的json数据格式 {"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"} {"userExsit":false,"msg":"用户名可用"} */ var span = $("#check_username_msg"); $.post("findUserServlet",{username:username},function (data) { if(data.userExsit) { // 用户名存在 span.css("color", "red"); span.html(data.msg); } else { span.css("color", "green"); span.html(data.msg); } },"json"); }); }); </script> </head> <body> <form> <input type="text" placeholder="请输入用户名" id="username" /> <span id="check_username_msg"></span> <br /> <input type="password" placeholder="请输入密码" id="password"> <br /> <input type="button" value="注册"> </form> </body> </html>
package com.heboan.www; import com.fasterxml.jackson.databind.ObjectMapper; 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; import java.util.HashMap; @WebServlet("/findUserServlet") public class findUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户名 String username = request.getParameter("username"); /* 期望服务器响应回的数据格式: {"userExsit":true,"msg":"此用户名太受欢迎,请更换一个"} {"userExsit":false,"msg":"用户名可用"} */ HashMap<String, Object> map = new HashMap<>(); // 设置响应的数据格式为json response.setContentType("application/json;charset=utf-8"); if ("heboan".equals(username)) { map.put("userExsit", true); map.put("msg", "此用户名太受欢迎,请更换一个"); } else { map.put("userExsit", false); map.put("msg", "用户名可用"); } // 将map转为json,并且传递给客户端 ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(response.getWriter(),map); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
每天进步一点,加油!