2024.3.22 Friday
接上文【WEEK4】 【DAY4】AJAX第一部分【中文版】
目录
- 8.4.Ajax异步加载数据
- 8.4.1.新建User.java
- 8.4.2.在pom.xml中添加lombok、jackson支持
- 8.4.3.更改tomcat设置
- 8.4.4.修改AjaxController.java
- 8.4.5.新建test2.jsp
- 8.4.5.1.注意:和WEB-INF平级!
- 8.4.5.2.验证点击事件
- 8.4.5.3.输出userList的内容
- 8.4.5.4.修改JavaScript版本
- 8.4.5.5.再修改test2.jsp,使userList直接在网页上显示
- 8.4.6.运行
- 8.5.Ajax验证用户名体验
- 8.5.1.修改AjaxController.java
- 8.5.2.新建login.jsp
- 8.5.3.运行
- 8.6.获取百度接口demo
8.4.Ajax异步加载数据
8.4.1.新建User.java
package P24.project;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private String name;private int age;private String gender;
}
8.4.2.在pom.xml中添加lombok、jackson支持
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>SpringMVC_try1</artifactId><groupId>com.kuang</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><groupId>P24</groupId><artifactId>springmvc-06-ajax</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.2</version></dependency></dependencies></project>
8.4.3.更改tomcat设置
初始情况下Application context的默认值为/springmvc_06_ajax_war_exploded,可以修改为/,简化url。
8.4.4.修改AjaxController.java
package P24.controller;import P24.project.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;//不返回到视图解析器
@RestController
public class AjaxController {@RequestMapping("/t1")public String test(){return "hello";}@RequestMapping("/a1")public void a(String name, HttpServletResponse response) throws IOException {System.out.println("a1:param=>"+name);if ("zzz".equals(name)){response.getWriter().print("true");}else {response.getWriter().print("false");}}@RequestMapping("/a2")public List<User> a2(){List<User> userList = new ArrayList<User>();//添加数据userList.add(new User("zhangsan",11,"male"));userList.add(new User("lisi",22,"female"));userList.add(new User("wangwu",33,"male"));return userList;}
}
8.4.5.新建test2.jsp
8.4.5.1.注意:和WEB-INF平级!
否则无法通过更改url访问jsp文件!(如下图)将出现404的问题【因为位置错误导致的404找了几乎一天,实际上只需要在创建时注意好即可!】
如果无意之间把test2.jsp放在了WEB-INF/jsp目录下其实也可以访问(不推荐),步骤如下:
- 修改AjaxController.jsp,将代码改为使用视图解析器的方式
- 创建方法t2访问test2,此时,通过视图解析器即可访问到WEB-INF/jsp/test2.jsp
package P24.controller;import P24.project.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;@Controller //会返回到视图解析器
//@RestController //不返回到视图解析器// 如果需要从控制器访问test2.jsp,则需要使用applicationContext.xml中的视图解析器
// 在此情况下,最外层AjaxController方法需要使用@Controller注释@GetMapping("/t2")public String t2(){return "/WEB-INF/test2.jsp";}
}
- 其他方式可参考以下链接进行修改,注意idea项目 的真实保存地址,不能在tomcat的保存地址进行操作(更不推荐,个人觉得很繁琐)
https://www.cnblogs.com/jet-angle/p/11477297.html
https://www.cnblogs.com/atsong/p/13118155.html
8.4.5.2.验证点击事件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script><script>$(function () {$("#btn").click(function (){console.log("test2");})});</script>
</head><body>
<%--先获取事件--%>
<input type="button" value="加载数据" id="btn">
<%--用table展示页面--%>
<table><tr><td>姓名</td><td>年龄</td><td>性别</td></tr><tbody><%--数据在后台,无法直接获取,所以需要使用“请求”--%></tbody>
</table>
</body>
</html>
http://localhost:8080/springmvc_06_ajax_war_exploded/test2.jsp
F12加载出console页,然后点击“加载数据”即可看到console.log(“test2”);被运行,输出“test2”
8.4.5.3.输出userList的内容
只需要将上一步的function进行修改
<script>$(function () {$("#btn").click(function (){//$.post(url, param[可省略], success)$.post("${pageContext.request.contextPath}/a2",function(data){console.log(data);})})});</script>
http://localhost:8080/springmvc_06_ajax_war_exploded/test2.jsp
8.4.5.4.修改JavaScript版本
如图,目前一般都是默认6+
8.4.5.5.再修改test2.jsp,使userList直接在网页上显示
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script><script>$(function () {$("#btn").click(function (){//$.post(url, param[可省略], success)$.post("${pageContext.request.contextPath}/a2",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>" +"<td>" + data[i].sex + "</td>" +"</tr>"}$("#content").html(html); //将var html="<>";中的元素放入这行});})});</script>
</head><body>
<%--先获取事件--%>
<input type="button" value="加载数据" id="btn">
<%--用table展示页面--%>
<table><tr><td>姓名</td><td>年龄</td><td>性别</td></tr><tbody id="content"><%--数据在后台,无法直接获取,所以需要使用“请求”--%></tbody>
</table>
</body>
</html>
8.4.6.运行
http://localhost:8080/springmvc_06_ajax_war_exploded/test2.jsp
8.5.Ajax验证用户名体验
8.5.1.修改AjaxController.java
package P24.controller;import P24.project.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;//@Controller //会返回到视图解析器
@RestController //不返回到视图解析器
public class AjaxController {@RequestMapping("/t1")public String test(){return "hello";}// 如果需要从控制器访问test2.jsp,则需要使用applicationContext.xml中的视图解析器
// 在此情况下,最外层AjaxController方法需要使用@Controller注释
// @GetMapping("/t2")
// public String t2(){
// return "/WEB-INF/test2.jsp";
// }@RequestMapping("/a1")public void a(String name, HttpServletResponse response) throws IOException {System.out.println("a1:param=>"+name);if ("zzz".equals(name)){response.getWriter().print("true");}else {response.getWriter().print("false");}}@RequestMapping("/a2")public List<User> a2(){List<User> userList = new ArrayList<User>();//添加数据userList.add(new User("zhangsan",11,"male"));userList.add(new User("lisi",22,"female"));userList.add(new User("wangwu",33,"male"));return userList;}@RequestMapping("/a3")public String a3(String name, String pwd){String msg = "";if (name != null){//admin这些数据应该在数据库中if ("admin".equals(name)){msg = "Accepted";}else {msg = "name have an error";}}if (pwd != null){//123456这些数据应该在数据库中if ("123456".equals(pwd)){msg = "Accepted";}else {msg = "password has an error";}}return msg;}
}
8.5.2.新建login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.7.1.js"></script><script>function a1(){$.post({url:"${pageContext.request.contextPath}/a3",data:{'name':$("#name").val()},success:function (data) {if (data.toString()=='Accepted'){$("#userInfo").css("color","green");}else {$("#userInfo").css("color","red");}$("#userInfo").html(data); //在网页上打印出data}});}function a2() {$.post({url:"${pageContext.request.contextPath}/a3",data:{'pwd':$("#pwd").val()},success:function (data) {if (data.toString()=='Accepted'){$("#pwdInfo").css("color","green");}else {$("#pwdInfo").css("color","red");}$("#pwdInfo").html(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>
8.5.3.运行
http://localhost:8080/springmvc_06_ajax_war_exploded/login.jsp
8.6.获取百度接口demo
<!DOCTYPE HTML>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>JSONP百度搜索</title><style>#q{width: 500px;height: 30px;border:1px solid #ddd;line-height: 30px;display: block;margin: 0 auto;padding: 0 10px;font-size: 14px;}#ul{width: 520px;list-style: none;margin: 0 auto;padding: 0;border:1px solid #ddd;margin-top: -1px;display: none;}#ul li{line-height: 30px;padding: 0 10px;}#ul li:hover{background-color: #f60;color: #fff;}</style><script>// 2.步骤二// 定义demo函数 (分析接口、数据)function demo(data){var Ul = document.getElementById('ul');var html = '';// 如果搜索数据存在 把内容添加进去if (data.s.length) {// 隐藏掉的ul显示出来Ul.style.display = 'block';// 搜索到的数据循环追加到li里for(var i = 0;i<data.s.length;i++){html += '<li>'+data.s[i]+'</li>';}// 循环的li写入ulUl.innerHTML = html;}}// 1.步骤一window.onload = function(){// 获取输入框和ulvar Q = document.getElementById('q');var Ul = document.getElementById('ul');// 事件鼠标抬起时候Q.onkeyup = function(){// 如果输入框不等于空if (this.value != '') {// ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆JSONPz重点☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆// 创建标签var script = document.createElement('script');//给定要跨域的地址 赋值给src//这里是要请求的跨域的地址 我写的是百度搜索的跨域地址script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';// 将组合好的带src的script标签追加到body里document.body.appendChild(script);}}}</script>
</head><body>
<input type="text" id="q" />
<ul id="ul"></ul>
</body>
</html>