文章目录
一、Ajax简介( Asynchronous JavaScript and XML)
- Ajax就是在无需重新加载网页的情况下,能够部分更新网页的技术。
- Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
- 使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
- 使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。
Ajax的使用场景:
搜索时搜索补全:
二、使用JQuery开发ajax
搭建测试环境
- 新建一个Module
SpringMVC-Ajax
- 配置
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置servlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--设置编码-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- 新建一个
pojo和controller
//pojo
package com.zyh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
//controller
package com.zyh.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {
}
- 创建Spring配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--需要配置的->注解驱动、静态资源过滤、视图解析器 -->
<context:component-scan base-package="com.zyh.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<!--处理JSON乱码-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
案例一:
- 编写
AjaxController
@RequestMapping("/t2")
public void test2(String name, HttpServletResponse response) throws IOException {
System.out.println("parm=>" + name);
if ("zyh".equals(name)) {
response.getWriter().print(true);
} else {
response.getWriter().print(false);
}
}
- 编写
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax</title>
<%--导入jquery--%>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
<script>
function a() {
$.post({
url: "${pageContext.request.contextPath}/t2",
data: {"name": $("#username").val()},
success: function (data, status) {
console.log("data=>" + data);
console.log("status=>" + status);
}
})
}
</script>
</head>
<body>
<%--丢失鼠标焦点的事件--%>
<input type="text" id="username" onblur="a()">
</body>
</html>
- 启动Tomcat测试
结果:
案例二:SpringMVC版
- 编写实体类:
User
package com.zyh.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
- 编写controller
@RequestMapping("/t3")
public List<User> test3() {
List<User> userList = new ArrayList<User>();
userList.add(new User("德莱厄斯", 22, "男"));
userList.add(new User("厄斐琉斯", 16, "男"));
userList.add(new User("马尔扎哈", 999, "男"));
return userList;
}
- 编写页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
<script>
$(function () {
$("#btn").click(function () {
$.post("${pageContext.request.contextPath}/t3", function (data) {
var html = "";
for (let i = 0; i < data.length; i++) {
html += "<tr>" +
"<td>" + data[i].name + "</td>" +
"<td>" + data[i].age + "</td>" +
"<td>" + data[i].sex + "</td>" +
"</tr>"
}
$("#content").html(html);
});
});
});
</script>
</head>
<body>
<input type="button" id="btn" value="加载数据">
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<%--加载后台数据--%>
<tbody id="content">
</tbody>
</table>
</body>
</html>
测试:
案例三:注册账户提示
- 编写Controller
@RequestMapping("/t4")
public String test4(String name, String password) {
String msg = "";
if (name != null) {
if ("admin".equals(name)) {
msg = "OK";
} else {
msg = "输入的用户名错误!";
}
}
if (password != null) {
if ("123456".equals(password)) {
msg = "OK";
} else {
msg = "输入的密码错误!";
}
}
return msg;
}
- 编写前端页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src=${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js></script>
<script>
function a1() {
$.post({
url: "${pageContext.request.contextPath}/t4",
data: {"name": $("#username").val()},
success: function (data) {
if (data.toString() === "OK") {
$("#userInfo").css("color", "green");
} else {
$("#userInfo").css("color", "red");
}
$("#userInfo").html(data);
}
});
}
function a2() {
$.post({
url: "${pageContext.request.contextPath}/t4",
data: {"password": $("#password").val()},
success: function (data) {
if (data.toString() === "OK") {
$("#pwdInfo").css("color", "green");
} else {
$("#pwdInfo").css("color", "red");
}
$("#pwdInfo").html(data);
}
});
}
</script>
</head>
<body>
<p>
用户名<input type="text" id="username" onblur="a1()">
<span id="userInfo"></span>
</p>
<p>
密码<input type="text" id="password" onblur="a2()">
<span id="pwdInfo"></span>
</p>
</body>
</html>
- 启动Tomcat测试: