Ajax的基础使用
简介:Ajax即Asynchronous Javascript And XML(异步JavaScript和XML)在 2005年被Jesse James Garrett提出的新术语,用来描述一种使用现有技术集合的‘新’方法,包括: HTML 或 XHTML, CSS, JavaScript, DOM, XML, XSLT, 以及最重要的XMLHttpRequest。 使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载(刷新)整个页面,这使得程序能够更快地回应用户的操作。
在以前没有ajax的时候,前后端的交互需要使用到,JSP,然后了JSP还是要由后端程序员来写,极大的提高了后端程序员的工作量,降低的开发效率。
有了ajax这种异步请求工具之后,后端程序员就不在需要使用到JSP了,前端的html页面可以通过ajax的异步请求与后端直接联系,这样前后端的分工就更加明确了。
我们通过一个例子来讲解ajax的使用吧。
项目创建
第一步:
第二步:
添加配置文件各种依赖
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>AjaxStudy</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>AjaxStudy Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </build> </project>
第三步:
AjaxServlet
package com.jakelihua.servlet; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.IOException; @WebServlet("/ajaxServlet") public class AjaxServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1. 响应数据 response.getWriter().write("hello ajax~"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
第四步:
进入w3c官网查看教程
https://www.w3school.com.cn/js/js_ajax_intro.asp
- 创建核心对象
var xhttp; if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
- 发送请求
xhttp.open("GET", "http://localhost:8080/AjaxStudy/ajaxServlet"); xhttp.send();
- 获取响应
xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); // 我们这里显示一下这个后端反馈的文本 } };
完整代码:
<!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/AjaxStudy/ajaxServlet"); xhttp.send(); // 3. 获取响应 xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); } }; </script> </body> </html>
运行结果:
案例
这个案例的目的就是完成我们常见的像百度啊,那种点击搜索栏就会出现提示词那种异步请求,网页没有刷新,但是确实响应了,然后紧跟时代,这个案例我使用SpringBoot来做,最开始用的还是传统的MVC,但是说实话,太麻烦了,一大堆配置,调试都要半天。
数据库建表语句
/* Navicat MySQL Data Transfer Source Server : 本机 Source Server Type : MySQL Source Server Version : 80024 Source Host : localhost:3306 Source Schema : projectdatabase Target Server Type : MySQL Target Server Version : 80024 File Encoding : 65001 Date: 11/01/2023 20:27:49 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int NOT NULL AUTO_INCREMENT, `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES (1, 'LIHUA', '123456'); INSERT INTO `user` VALUES (2, 'zhangsan', '123'); INSERT INTO `user` VALUES (3, 'LISI', '456489'); INSERT INTO `user` VALUES (4, 'heheheh', '123456'); INSERT INTO `user` VALUES (5, 'ahuang', '123'); INSERT INTO `user` VALUES (6, 'dsdad', '154654'); SET FOREIGN_KEY_CHECKS = 1;
项目结构
一定注意一点,就是这个后端的java类,一定要写在Springbootlogincheck包下面,不然会导致网址访问不到404错误。
User类
package com.example.springbootlogincheck.Bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String username; private String password; }
IndexController类
package com.example.springbootlogincheck.Controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController { @RequestMapping("/") public String index(){ return"admin/register.html"; } }
UserController
package com.example.springbootlogincheck.Controller; import com.example.springbootlogincheck.Bean.User; import com.example.springbootlogincheck.Dao.UserDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @Controller public class UserController { @Autowired UserDao userDao; @ResponseBody @GetMapping("/selectUser") public String SelectUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); boolean flag = false; List<User> list = userDao.selectList(null); for (User user : list){ if (user.getUsername().equals(username)){ flag = true; } } if (flag) { // 如果查到了就返回true字符串 反之就是false字符串 return "true"; } return "false"; } }
UserDao
package com.example.springbootlogincheck.Dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.springbootlogincheck.Bean.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserDao extends BaseMapper<User> { }
前端网页
register.css
* { margin: 0; padding: 0; list-style-type: none; } .reg-content{ padding: 30px; margin: 3px; } a, img { border: 0; } body { background-image: url("../imgs/reg_bg_min.jpg") ; text-align: center; } table { border-collapse: collapse; border-spacing: 0; } td, th { padding: 0; height: 90px; } .inputs{ vertical-align: top; } .clear { clear: both; } .clear:before, .clear:after { content: ""; display: table; } .clear:after { clear: both; } .form-div { background-color: rgba(255, 255, 255, 0.27); border-radius: 10px; border: 1px solid #aaa; width: 424px; margin-top: 150px; margin-left:1050px; padding: 30px 0 20px 0px; font-size: 16px; box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3); text-align: left; } .form-div input[type="text"], .form-div input[type="password"], .form-div input[type="email"] { width: 268px; margin: 10px; line-height: 20px; font-size: 16px; } .form-div input[type="checkbox"] { margin: 20px 0 20px 10px; } .form-div input[type="button"], .form-div input[type="submit"] { margin: 10px 20px 0 0; } .form-div table { margin: 0 auto; text-align: right; color: rgba(64, 64, 64, 1.00); } .form-div table img { vertical-align: middle; margin: 0 0 5px 0; } .footer { color: rgba(64, 64, 64, 1.00); font-size: 12px; margin-top: 30px; } .form-div .buttons { float: right; } input[type="text"], input[type="password"], input[type="email"] { border-radius: 8px; box-shadow: inset 0 2px 5px #eee; padding: 10px; border: 1px solid #D4D4D4; color: #333333; margin-top: 5px; } input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus { border: 1px solid #50afeb; outline: none; } input[type="button"], input[type="submit"] { padding: 7px 15px; background-color: #3c6db0; text-align: center; border-radius: 5px; overflow: hidden; min-width: 80px; border: none; color: #FFF; box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3); } input[type="button"]:hover, input[type="submit"]:hover { background-color: #5a88c8; } input[type="button"]:active, input[type="submit"]:active { background-color: #5a88c8; } .err_msg{ color: red; padding-right: 170px; } #password_err,#tel_err{ padding-right: 195px; } #reg_btn{ margin-right:50px; width: 285px; height: 45px; margin-top:20px; } #checkCode{ width: 100px; } #changeImg{ color: aqua; }
img
a.jpg
reg_bg_min.jpg
register.html
js部分
在这个js部分里面,一个点需要注意一下,就是这个responseText这个属性,这个属性接受的值首先是String类型,然后了,这个值就是访问的链接下对应的方法的返回值的对应的String类型格式。
<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) { //alert(this.responseText); //判断 if(this.responseText == "true"){ //用户名存在,显示提示信息 document.getElementById("username_err").style.display = ''; }else { //用户名不存在 ,清楚提示信息 document.getElementById("username_err").style.display = 'none'; } } }; } </script>
完整代码:
<!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) { //alert(this.responseText); //判断 if(this.responseText == "true"){ //用户名存在,显示提示信息 document.getElementById("username_err").style.display = ''; }else { //用户名不存在 ,清楚提示信息 document.getElementById("username_err").style.display = 'none'; } } }; } </script> </body> </html>
效果展示:
如果输入的账户在失去焦点之后,发现这个用户没有在数据库中存在就不会发生啥。
如果存在的话就显示这个信息,已经存在了。