学习笔记——ajax,axios
一、学习总结

二、学习内容
案例一
package com.jsoft.afternoon;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
package com.jsoft.morning.entity;
import java.util.List;
public class Student {
private Integer id;
private String name;
private List<Student> list;
public Student() {
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
this.list = list;
}
public List<Student> getList() {
return list;
}
public void setList(List<Student> list) {
this.list = list;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.jsoft.morning;
import com.alibaba.fastjson.JSON;
import com.jsoft.morning.entity.Student;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
list.add(new Student(1001,"zhangsan1"));
list.add(new Student(1002,"zhangsan2"));
list.add(new Student(1003,"zhangsan3"));
list.add(new Student(1004,"zhangsan4"));
Student student = new Student();
student.setId(1001);
student.setName("ahahah");
student.setList(list);
System.out.println(JSON.toJSONString(student));
}
}
后端代码
package com.jsoft.morning.servlet;
import com.alibaba.fastjson.JSON;
import com.jsoft.morning.entity.Student;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@WebServlet(name = "ListStudentServlet", value = "/list.do")
public class ListStudentServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> stus = Arrays.asList("aaa","bbb","ccc","ddd","eee","fff");
PrintWriter out = response.getWriter();
Student student = new Student(1001,"zhangsan");
List<Student> list = new ArrayList<>();
list.add(new Student(1001,"zhangsan1"));
list.add(new Student(1002,"zhangsan2"));
list.add(new Student(1003,"zhangsan3"));
list.add(new Student(1004,"zhangsan4"));
student.setList(list);
out.print(JSON.toJSONString(student));
/**
* json串的格式:键值对
*
* {"id":1001,"name":"zhangsan","stus":{aaa,bbb,ccc...}}
*
* */
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="showStu">显示学生列表</button>
<div id="info">
</div>
<script src="static/js/jquery-3.0.0.min.js"></script>
<script>
$(function(){
$("#showStu").click(function() {
$.ajax({
url:"list.do",
type : "get",
// dataType的默认值是字符串
// json串
dataType: "json",
success:function(data) {
// console.log(data);
// console.log(data.id);
// console.log(data.name);
// console.log(data.list);
$.each(data.list,function(index,item) {
$("#info").append(
item.id + "---" + item.name + " <br> "
);
})
// let info = $("#info");
// for(let i = 0;i < data.length;i++){
// console.log(i);
// }
}
});
});
})
</script>
</body>
</html>
案例二
需求
在后台准备一个map集合,
key:城市
value:天气
当点击搜索按钮,把文本框输入的城市发送到后台,在后台接收城市名称
根据城市名称去map集合中获取对应的天气,再把天气返回给前台。
展示到下方的span中。
点击这5个超链,也可以获取对应的城市天气!
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<input type="text" v-model="name" @keyup.delete="shows" @input="shows" @keyup.enter="searchCity">
<input type="button" value="搜索" @click="searchCity"><br>
<span v-for="city in hotCitys">
<a href="" @click.prevent="searchCity1(city)" >
{{city}}
</a>
</span>
<hr>
<span v-show="isShow">{{name}},今天的天气是:{{message}}</span>
</div>
<script src="../static/js/vue.js"></script>
<script src="../static/js/axios.min.js"></script>
<script>
const app = new Vue({
el:"#app",
data:{
hotCitys:["北京","上海","广州","深圳","杭州"],
name:"",
message:"",
isShow: false,
},
methods:{
shows() {
this.isShow = false;
},
searchCity(){
// 回调函数的写法
// 正常的匿名函数:this指向的就是函数的调用者
// 箭头函数:this还是之前的this
// 记忆点:只要是写了function,this就会变化。
// 推荐使用箭头函数
let _this = this;
axios.get("weather.do?name="+this.name).then(function (response) {
_this.message = response.data;
_this.isShow = true;
});
},
searchCity1(name) {
// 接收传递过来的参数
// 把传递过来的参数给我们vue实例中的name赋值
this.name = name;
// 调用之前写好的搜索城市的方法
this.searchCity();
},
}
});
</script>
</body>
</html>
后端代码
package com.jsoft.morning.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@WebServlet(name = "WeatherServlet", value = "/weather.do")
public class WeatherServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String,String> map = new HashMap<>();
map.put("北京","晴转多云,空气清新");
map.put("上海","天气炎热");
map.put("广州","大到暴雨");
map.put("深圳","瞬间风力可达9级");
map.put("杭州","阴雨连绵");
map.put("长春","秋高气爽");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String weather = map.get(name);
response.setCharacterEncoding("utf-8");
response.addHeader("content-type","text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(weather);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
三、笔记内容
4种发请求的方式:
1、地址栏
2、a标签
3、form表单
4、location.href或window.open()
ajax(Jquery):
异步刷新(局部刷新),前端技术。给后台发请求。
异步:整个页面不会全部刷新,只有某个局部在刷新。
验证用户名是否存在。
刷新注意点:
注意点一:
使用ajax发送请求,页面是不可以通过后台跳转!!!
如果需要跳页面,也是通过我们前端的JS来跳转,不可能通过servlet跳转
注意点二
ajax和form表单不能同时使用。
ajax:不跳页面。
form:一定跳走的。
请求体:post请求才有请求体。
ajax发起请求,后台给出的响应会回到ajax的响应处理函数中。
readyState:
0: xhr被创建成功,open方法未调用
1: open被调用,建立的连接
2: send被调用,可以获取状态行和响应头
3: 可以拿到响应体,响应体加载中
4: 响应体下载完成,可以直接使用responseText。
代表请求可以正常发送,响应能够正常接收。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>
账号:<input type="text" id="username"><span id="msg"></span>
</p>
<input type="button" onclick="valid()" value="验证">
<script>
function valid() {
let username = document.querySelector("#username").value;
let msg = document.querySelector("#msg");
// 向后台发请求
// 使用ajax,JS原生的ajax
// XMLHttpRequest是ajax的支持对象
let xhr = new XMLHttpRequest();
// console.log(xhr.readyState + "....0");
// 设置请求的方式和url地址
// xhr.open("GET","valid.do?username=" + username);
// console.log(xhr.readyState + "....1")
// 发送POST请求
xhr.open("POST","valid.do");
// POST请求需要设置一下请求头信息
// Content-type,发送的请求的内容的类型
// application/x-www-form-urlencoded 文档流
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 发请求,并且设置请求体
xhr.send("username=" + username + "&password=123456");
// 指定xhr状态变化的处理函数
xhr.onreadystatechange = function() {
// console.log(this.readyState);
// 正常接收后台的响应
if(this.readyState === 4) {
// 通过xhr的responseText获取到对应的响应体
// console.log(this.responseText);
switch (this.responseText) {
case "1":
msg.innerHTML = "用户名可用";
break;
case "0":
msg.innerHTML = "用户名已存在";
}
}
}
}
</script>
</body>
</html>
formData/发送请求(Jquery)
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
账号:<input type="text" id="username"><span id="msg"></span>
<button id="validBtn">验证</button>
<script src="static/js/jquery-3.0.0.min.js"></script>
<script>
$(function() {
$("#validBtn").click(function() {
let username = $("#username").val();
let password = "123456";
// formData构建一个表单数据对象
// formData是JS的内置对象,和JQuery无关,和Vue无关
let formData = new FormData();
formData.append("username",username);
formData.append("password",password);
// 发送ajax请求
// 3.完整写法
$.ajax({
url: "valid.do",
type: "post",
data: formData,
success : function(res) {
console.log(res);
},
error : function(res) {
console.log(res);
}
});
// 2.发送post请求
// $.post("valid.do","username=" + username,function (data) {
// if(data == "1") {
// $("#msg").html("用户名可用...")
// }
// if(data == "0") {
// $("#msg").html("用户名已存在...")
// }
// });
// 1.发送get请求
// $.get("valid.do?username=" + username,function(data) {
// // data就是后台回来的响应体
// console.log(data);
// if(data == "1") {
// $("#msg").html("用户名可用...")
// }
// if(data == "0") {
// $("#msg").html("用户名已存在...")
// }
// });
});
})
</script>
</body>
</html>
后端代码
package com.jsoft.morning.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;
@WebServlet(name = "ValidServlet", value = "/valid.do")
public class ValidServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("valid.do已经接受到请求...");
PrintWriter out = response.getWriter();
// 后台给前台AJAX的响应
String username = request.getParameter("username");
// String password = request.getParameter("password");
// System.out.println(username + "->" + password);
// int i = 10 / 0;//测试
if(Objects.equals(username,"admin")){
// 0代表不可用 1代表可用
out.write("0");
}else {
out.write("1");
}
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
axios(Vue)
axios:对原生ajax的一个封装。
ES6语法。Promise语法。
axios发送请求
axios发送get请求,
请求中如果有参数,还是一个默认的以文档里的形式发送,和之前的任何一种请求方式没有任何区别。
axios发送post请求,
请求中如果有参数,会把post请求的请求体转成json串,然后再发给后台。
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<button @click="get">axios_get</button>
<button @click="post">axios_post</button>
</div>
<script src="static/js/vue.js"></script>
<script src="static/js/axios.min.js"></script>
<script>
const app = new Vue({
el:"#app",
data:{},
methods:{
post(){
// 发送post请求
axios.post("vue.do",{
"username":"xiaoqiang",
"password":"000000"
},function(response){
console.log(response);
});
},
get(){
// 发送get请求
axios.get("vue.do?username=admin&password=666666").then(function(response){
console.log(response);
console.log(response.data);
}).catch(function(err){
console.log(err);
});
}
},
});
</script>
</body>
</html>
1、get请求,后台没有对应的对象来封装,不能有私密数据。
2、post请求,后台都是有对象跟着的。
username,password------------------User
id,name,age,gender,email-----------Student
rquest.getParameter()方法只能接收默认的文档流中的参数,接不了json串。
String username = request.getParameter("username");
System.out.println("username--->" + username);
后端代码
package com.jsoft.morning.servlet;
import com.alibaba.fastjson.JSON;
import com.jsoft.afternoon.User;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "VueServlet", value = "/vue.do")
public class VueServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("vueSevlet已经接到了请求...");
// 从request中获取了一个流,缓冲字符输入流
BufferedReader reader = request.getReader();
String line = reader.readLine();
System.out.println(line);
/*
封装对象的前提:
json串中的数据的key和对象的属性名要一致。
是根据set方法的名封装的。
*/
User user = JSON.parseObject(line, User.class);
System.out.println(user);
// String sql = "select * from user where username = ? and password = ?"
// userdao.get(sql,user.getUsername(),user.getPassword());
PrintWriter out = response.getWriter();
out.print("hello axios and vue...");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}

浙公网安备 33010602011771号