Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页,能够更新部分网页的技术
Ajax 不是编程语言,而是一种用于创建更好更快以及交互性更强的 Web 应用程序技术
使用 Ajax 技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新
pom.xml:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.51</version>
</dependency>
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"
metadata-complete="true">
<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>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
<context:component-scan base-package="com.demo.controller"/>
<!-- 让SpringMVC不处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- <!– 支持MVC注解驱动 –>-->
<!-- <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 class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
text.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script>
function go(){
var url = document.getElementById("url").value;
document.getElementById("iframe").src = url;
}
</script>
</head>
<body>
<div>
<p>输入地址:</p>
<p>
<input type="text" id="url" value="https://www.4399.com/"/>
<input type="button" value="提交" onclick="go()"/>
</p>
</div>
<div>
<iframe id="iframe" style="width: 100%;height: 500px"></iframe>
</div>
</body>
</html>
效果如下:
(上述仅实现类似异步的模样,局部改变)
官网下载 jquery,放到 js 目录下
AjaxController.java:
package com.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class AjaxController {
@RequestMapping("/ajax")
public void test(String name, HttpServletResponse response) throws IOException {
System.out.println(name);
if("张三".equals(name)){
response.getWriter().println("true");
}else {
response.getWriter().println("false");
}
}
}
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/ajax",
data:{"name":$("#username").val()},
success:function(data){
alert(data);
}
})
}
</script>
</head>
<body>
用户名:<input type="text" id="username" onblur="a()">
</body>
</html>
效果如下:
XMLHttpRequest(简称 xhr),是浏览器提供的 JS 对象,通过它可以请求到服务器上的数据资源
xhr 允许进行异步请求,它可以在后台执行,而不会阻止页面的其他操作
Ajax 异步加载数据:
User.java:
package com.demo.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
AjaxController.java:
package com.demo.controller;
import com.demo.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class AjaxController {
@RequestMapping("/list")
public List<User> list(){
List<User> arrayList = new ArrayList<User>();
//添加数据
arrayList.add(new User("张三1",3));
arrayList.add(new User("张三2",3));
return arrayList;
}
}
list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
$(function(){
$("#btn").click(function(){
$.post("${pageContext.request.contextPath}/list",function (data){
//console.log(data);
var html="";
for(let i = 0;i < data.length;i++){
html += "<tr>" +
"<td>" + data[i].name + "</td>" +
"<td>" + data[i].age + "</td>" +
"</tr>"
}
$("#content").html(html);
})
})
});
</script>
</head>
<body>
<input type="button" value="加载数据" id="btn"/>
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
<tbody id="content"></tbody>
</table>
</body>
</html>
效果如下:
Ajax 验证用户名:
login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/login",
data:{"name":$("#name").val()},
success:function(data){
console.log(data);
}
})
}
function a2(){
$.post({
url:"${pageContext.request.contextPath}/login",
data:{"pwd":$("#pwd").val()},
success:function(data){
console.log(data);
}
})
}
</script>
</head>
<body>
<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userInfo"></span>
</p>
<p>
密码:<input type="text" id="pwd" onblur="a2()"/>
<span id="pwdInfo"></span>
</p>
</body>
</html>
AjaxController.java:
package com.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AjaxController {
@RequestMapping("/login")
public String login(String name,String pwd) {
String msg = "";
if (name != null) {
if ("admin".equals(name)) {
msg = "true";
} else {
msg = "用户名错误";
}
}
if(pwd != null){
if("123".equals(pwd)){
msg = "true";
} else {
msg = "密码错误";
}
}
return msg;
}
}
效果如下: