文章目錄
一、初始AJAX
1、什麼是AJAX呢?
-
AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)。
-
AJAX 是一種用於創建快速動態網頁的技術。
-
AJAX 不是新的編程語言,而是一種使用現有標準的新方法。
2、爲什麼要使用AJAX呢?解決了什麼樣的問題?
傳統的網頁(不使用 AJAX)如果需要更新內容,必需重載整個網頁面。
使用AJAX後:通過在後臺與服務器進行少量數據交換,AJAX 可以使網頁實現異步更新。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
3、AJAX的核心?
Ajax的核心是XMLHttpRequest對象(XHR)。XHR用於在後臺與服務器交換數據。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。
二、案例演示
1、僞造AJAX
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>僞造AJAX</title>
</head>
<body>
<div>
<p>
請輸入要加載的地址:<span id="currentTime"></span><br><br>
<input type="text" id="url" value="https://www.baidu.com/">
<input type="button" onclick="loadPage()" value="提交">
</p>
</div>
<div>
<h3>加載頁面的位置</h3>
<iframe width="80%" height="600px" id="iframePosition">
</iframe>
</div>
<script type="text/javascript">
window.onload = function f() {
var myDate = new Date();
document.getElementById("currentTime").innerText = myDate.getTime();
};
function loadPage() {
var targetURL = document.getElementById("url").value;
document.getElementById("iframePosition").src = targetURL;
}
</script>
</body>
</html>
這個案例演示了一個僞造的AJAX,在當前頁面下,我們並不需要去刷新瀏覽器,直接輸入地址,點擊提交就可以請求到一個頁面。
2、jQuery.ajax
方式一:使用原始的HttpServletResponse
(1)pom.xml
<!-- 版本鎖定 -->
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
(2) web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Spring MVC的核心控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Servlet的初始化參數,讀取Spring MVC的配置文件,創建Spring容器 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--表示容器在應用啓動時就加載並初始化這個servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(3)springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.uos"></context:component-scan>
<!--配置視圖解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--開啓Spring MVC基於註解的支持-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list><value>text/plain;charset=utf-8</value></list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
(4)編寫一個控制器
@Controller
@RequestMapping("/ajax")
public class AjaxController {
// 第一種方式:服務器要返回一個字符串,註解使用response
@RequestMapping("/a1")
public void ajax1(String name, HttpServletResponse response) throws IOException {
if ("admin".equals(name)) {
response.getWriter().print("true");
}else {
response.getWriter().print("false");
}
}
}
(5)編寫jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>AJAX</title>
</head>
<body>
用戶名:
<input type="text" id="txtName" onblur="a1()">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function a1() {
//ajax默認是get請求
$.ajax({
/*
* url:待載入頁面的地址
* data:待發送的key/value 參數
* success:載入成功時的回調函數
* data:封裝了服務器返回的數據
* status:狀態
* */
url:"${pageContext.request.contextPath}/ajax/a1",
data:{'name':$('#txtName').val()},
success:function (data,status) {
alert(data);
alert(status);
}
});
}
</script>
</body>
</html>
(6)效果演示
ajax默認是get請求,我們可以將$.ajax
修改爲$.post
進行驗證
方式二:Spring MVC實現
(1)編寫一個User實體類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
String name;
Integer age;
String sex;
}
(2)在控制器中添加以下方法
// 第二種方式:Spring MVC實現
@RequestMapping("/a2")
@ResponseBody
public List<User> ajax2() {
List<User> list = new ArrayList<User>();
list.add(new User("張三",12,"男"));
list.add(new User("李四",24,"男"));
list.add(new User("王五",18,"男"));
return list;
}
(3)編寫一個jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>AJAX</title>
</head>
<body>
<input type="button" id="btn" value="獲取數據"/>
<table width="80%" align="center">
<tr>
<td>姓名</td>
<td>年齡</td>
<td>性別</td>
</tr>
<tbody id="content">
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function () {
$("#btn").click(function () {
$.post("${pageContext.request.contextPath}/ajax/a2",function (data) {
console.log(data);
var html="";
for (var 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>
</body>
</html>
(4)效果演示
3、登錄提示效果
(1)在控制器中添加方法
@RequestMapping("/a3")
@ResponseBody
public String ajax3(String name,String pwd) {
String message = "";
if (name!=null) {
if ("admin".equals(name)) {
message = "OK";
}else {
message = "用戶名有誤";
}
}
if (pwd!=null) {
if ("123456".equals(pwd)) {
message = "OK";
}else {
message = "密碼有誤";
}
}
return message;
}
(2)編寫jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>註冊</title>
</head>
<body>
<p>
用戶名:
<input type="text" id="name" onblur="a1()">
<span id="nameInfo"></span>
</p>
<p>
密碼:
<input type="text" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
</p>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function a1() {
$.post({
url:"${pageContext.request.contextPath}/ajax/a3",
data:{'name':$('#name').val()},
success(data){
if (data.toString()=="OK") {//用戶名正確
$('#nameInfo').css("color","green");
}else {
$('#nameInfo').css("color","red");
}
$('#nameInfo').html(data);
}
})
}
function a2() {
$.post("${pageContext.request.contextPath}/ajax/a3",{'pwd':$('#pwd').val()},function(data){
if (data.toString()=="OK") {//密碼正確
$('#pwdInfo').css("color","green");
}else {
$('#pwdInfo').css("color","red");
}
$('#pwdInfo').html(data);
})
}
</script>
</body>
</html>
(3)效果演示
這個案例演示了在不刷新瀏覽器的情況下實現了登錄提示的效果。
三、總結
AJAX流程
在使用AJAX時,我們需要注意一下經常使用到的參數。
$.post({
/*
* url:待載入頁面的地址
* data:待發送的key/value 參數
* success:載入成功時的回調函數
* data:封裝了服務器返回的數據
* status:狀態
* */
})
學會使用AJAX後,再使用Vue就很簡單啦,其使用方法基本相同。