文章目錄
一、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測試: