AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 是一种用于创建快速动态网页的技术。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
使用AJAX后:通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
Ajax的核心是XMLHttpRequest对象(XHR)。XHR用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
<!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,在当前页面下,我们并不需要去刷新浏览器,直接输入地址,点击提交就可以请求到一个页面。
<properties>
<spring.version>5.0.2.RELEASEspring.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.16.10version>
<scope>providedscope>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
dependencies>
<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">
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<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>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list><value>text/plain;charset=utf-8value>list>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
beans>
@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");
}
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>AJAXtitle>
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>
ajax默认是get请求,我们可以将$.ajax
修改为$.post
进行验证
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
String name;
Integer age;
String sex;
}
// 第二种方式: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;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>AJAXtitle>
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+= "" +
"" + data[i].name + " " +
"" + data[i].age + " " +
"" + data[i].sex + " " +
" "
}
$("#content").html(html);
});
})
})
script>
body>
html>
@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;
}
<%@ 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>
AJAX流程
在使用AJAX时,我们需要注意一下经常使用到的参数。
$.post({
/*
* url:待载入页面的地址
* data:待发送的key/value 参数
* success:载入成功时的回调函数
* data:封装了服务器返回的数据
* status:状态
* */
})
学会使用AJAX后,再使用Vue就很简单啦,其使用方法基本相同。