Vue的Ajax請求
axios簡介
- ? Axios,是Web數(shù)據(jù)交互方式,是一個(gè)基于promise [5]的網(wǎng)絡(luò)請求庫,作用于node.js和瀏覽器中,它是 isomorphic 的(即同一套代碼可以運(yùn)行在瀏覽器和node.js中)。在服務(wù)端它使用原生node.js http模塊, 而在客戶端 (瀏覽端) 則使用XMLHttpRequest。 [2]
- axios :不是vue的插件,可以在任何地方使用,推薦
axios的使用方式
1、使用npm安裝
npm install axios
2、使用cdn鏈接axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios的語法
axios({
// 請求方式
method: 'post',
url: 'api',
// 傳遞參數(shù)
data: obj,
// 設(shè)置請求頭信息
headers: {
key: value
},
responseType: 'json'
}).then(response => {
// 請求成功
let res = response.data;
console.log(res);
}).catch(error => {
// 請求失敗,
console.log(error);
});
axios案例
1、數(shù)據(jù)準(zhǔn)備
- Student.json
[
{
"sid":1,
"name":"mary",
"age":18,
"gender":"女"
},
{
"sid":2,
"name":"lucy",
"age":18,
"gender":"女"
},
{
"sid":3,
"name":"tom",
"age":19,
"gender":"男"
},
{
"sid":4,
"name":"jack",
"age":18,
"gender":"男"
}
]
2、初使用問題
- VScode
- 解決辦法
3、axios 發(fā)送get請求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">
<tr>
<th>學(xué)號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
</tr>
<tr v-for="stu in stus">
<td>{{stu.sid}}</td>
<td>{{stu.name}}</td>
<td>{{stu.age}}</td>
<td>{{stu.gender}}</td>
</tr>
</table>
</div>
<script>
const vueApp = Vue.createApp({
data:function(){
return {
stus:""
}
},
created:function(){
//發(fā)送ajax請求,將得到的數(shù)據(jù)賦值給stus
axios({
method:"get",
url:"json/students.json"
}).then(resp => {
this.stus = resp.data;
});
}
});
vueApp.mount("#app");
</script>
</body>
</html>
- 或者
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">
<tr>
<th>學(xué)號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
</tr>
<tr v-for="stu in stus">
<td>{{stu.sid}}</td>
<td>{{stu.name}}</td>
<td>{{stu.age}}</td>
<td>{{stu.gender}}</td>
</tr>
</table>
</div>
<script>
const vueApp = Vue.createApp({
data:function(){
return {
stus:""
}
},
created:function(){
//發(fā)送ajax請求,將得到的數(shù)據(jù)賦值給stus
axios.get("json/students.json").then(resp => {
this.stus = resp.data;
});
}
});
vueApp.mount("#app");
</script>
</body>
</html>
4、axios 發(fā)送post請求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">
<tr>
<th>學(xué)號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
</tr>
<tr v-for="stu in stus">
<td>{{stu.sid}}</td>
<td>{{stu.name}}</td>
<td>{{stu.age}}</td>
<td>{{stu.gender}}</td>
</tr>
</table>
</div>
<script>
const vueApp = Vue.createApp({
data:function(){
return {
stus:""
}
},
created:function(){
//發(fā)送ajax請求,將得到的數(shù)據(jù)賦值給stus
axios({
method:"post",
url:"json/students.json"
}).then(resp => {
this.stus = resp.data;
});
}
});
vueApp.mount("#app");
</script>
</body>
</html>
- 注意:絕大多數(shù)web服務(wù)器,都不允許靜態(tài)文件響應(yīng)POST請求,所以這里運(yùn)行會(huì)報(bào)錯(cuò)哦。
5、補(bǔ)充
- 為所有支持的請求方法提供了別名
- axios.request(confifig)
- axios.get(url[, confifig])
- axios.delete(url[, confifig])
- axios.head(url[, confifig])
- axios.post(url[, data[, confifig]])
- axios.put(url[, data[, confifig]])
- axios.patch(url[, data[, confifig]])
請求后臺(tái)數(shù)據(jù)
1.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">
<tr>
<th>學(xué)號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>郵箱</th>
</tr>
<tr v-for="stu in stus">
<td>{{stu.sid}}</td>
<td>{{stu.sname}}</td>
<td>{{stu.sage}}</td>
<td>{{stu.sgender}}</td>
<td>{{stu.semail}}</td>
</tr>
</table>
</div>
<script>
const vueApp = Vue.createApp({
data:function(){
return {
stus:""
}
},
created:function(){
//發(fā)送ajax請求,將得到的數(shù)據(jù)賦值給stus
axios.get("http://localhost:8888/day10_war_exploded/studentServlet?flag=getAllStudents").then(resp => {
this.stus = resp.data;
});
}
});
vueApp.mount("#app");
</script>
</body>
</html>
2.StudentServlet.java
package com.etime.servlet;
import com.etime.entity.Student;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/studentServlet")
public class StudentServlet extends BaseServlet {
protected void getAllStudents(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
List<Student> list = new ArrayList<>();
Student student1 = new Student(1,"范冰冰","女",18,"fbb@qq.com");
Student student2 = new Student(2,"劉德華","男",18,"ldh@qq.com");
Student student3 = new Student(3,"孫紅雷","男",18,"shl@qq.com");
list.add(student1);
list.add(student2);
list.add(student3);
ObjectMapper mapper = new ObjectMapper();
String res = mapper.writeValueAsString(list);
PrintWriter out = resp.getWriter();
out.print(res);
out.close();
}
}
3.跨域問題
-
指的是瀏覽器不能執(zhí)行其他網(wǎng)站的腳本。它是由瀏覽器的同源策略造成的,是瀏覽器對javascript施加的安全限制。
-
同源策略:是指協(xié)議,域名,端口都要相同,其中有一個(gè)不同都會(huì)產(chǎn)生跨域,在請求數(shù)據(jù)時(shí),瀏覽器會(huì)在控制臺(tái)中報(bào)一個(gè)異常,提示拒絕訪問。
-
跨域問題怎么出現(xiàn)的?文章來源:http://www.zghlxwxcb.cn/news/detail-664988.html
- 開發(fā)一些前后端分離的項(xiàng)目,比如使用 Servlet + Vue 開發(fā)時(shí),后臺(tái)代碼在一臺(tái)服務(wù)器上啟動(dòng),前臺(tái)代碼在另外一臺(tái)電腦上啟動(dòng),此時(shí)就會(huì)出現(xiàn)問題。
- 比如:
- 后臺(tái) 地址為http://localhost:8080/
- 前臺(tái) 地址為 http://127.0.0.1:5500/
- 此時(shí)端口號不一致, 不符合同源策略,造成跨域問題。
-
CorsFilter文章來源地址http://www.zghlxwxcb.cn/news/detail-664988.html
package com.etime.filter;
import org.apache.commons.lang.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
跨域請求
*/
@WebFilter("/*")
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
request.setCharacterEncoding("utf-8");
// 不使用*,自動(dòng)適配跨域域名,避免攜帶Cookie時(shí)失效
String origin = request.getHeader("Origin");
if(StringUtils.isNotBlank(origin)) {
response.setHeader("Access-Control-Allow-Origin", origin);
}
// 自適應(yīng)所有自定義頭
String headers = request.getHeader("Access-Control-Request-Headers");
if(StringUtils.isNotBlank(headers)) {
response.setHeader("Access-Control-Allow-Headers", headers);
response.setHeader("Access-Control-Expose-Headers", headers);
}
// 允許跨域的請求方法類型
response.setHeader("Access-Control-Allow-Methods", "*");
// 預(yù)檢命令(OPTIONS)緩存時(shí)間,單位:秒
response.setHeader("Access-Control-Max-Age", "3600");
// 明確許可客戶端發(fā)送Cookie,不允許刪除字段即可
response.setHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
綜合練習(xí)
1.register.html–注冊功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>注冊</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<form>
賬號:<input type="text" v-model="username" @blur="checkUsername()">
<span style="color:red">{{username_msg}}</span><br>
密碼:<input type="password" v-model="pwd" @blur="checkPwd()">
<span style="color:red">{{pwd_msg}}</span><br>
<input type="button" value="注冊" @click="register()">
</form>
</div>
<script>
const vueApp = Vue.createApp({
data:function(){
return {
username:"",
pwd:"",
username_msg:"",
pwd_msg:"",
username_flag:false,
pwd_flag:false
}
},
methods:{
checkUsername:function(){
if (this.username == "") {
this.username_msg = "賬號不能為空";
this.username_flag = false;
} else if (this.username.length < 6) {
this.username_msg = "賬號至少6個(gè)字符";
this.username_flag = false;
} else {
//賬號是否為已注冊賬號的判斷
axios({
method:"get",
url:"http://localhost:8888/day10_war_exploded/managerServlet?flag=checkUsername&username="+this.username
}).then(resp => {
if (resp.data) {
this.username_msg = "";
this.username_flag = true;
} else {
this.username_msg = "賬號已存在";
this.username_flag = false;
}
});
}
},
checkPwd:function(){
if (this.pwd == "") {
this.pwd_msg = "密碼不能為空";
this.pwd_flag = false;
} else if (this.pwd.length < 8) {
this.pwd_msg = "密碼至少8個(gè)字符";
this.pwd_flag = false;
} else {
this.pwd_msg = "";
this.pwd_flag = true;
}
},
register:function(){
if (this.username_flag && this.pwd_flag) {
//處理需要傳遞給后端的數(shù)據(jù),使用這種方式處理數(shù)據(jù)時(shí),method值必須是post
let params = new URLSearchParams();
params.append("flag","register");
params.append("username",this.username);
params.append("pwd",this.pwd);
//數(shù)據(jù)全部通過校驗(yàn)
axios({
method:"post",
url:"http://localhost:8888/day10_war_exploded/managerServlet",
data:params
}).then(resp => {
if (resp.data) {
alert("注冊成功");
window.location.href = "login.html";
} else {
alert("注冊失敗,請稍后再試");
}
});
} else {
alert("請認(rèn)真填寫數(shù)據(jù)");
}
}
}
});
vueApp.mount("#app");
</script>
</body>
</html>
2.login.html-登錄功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登錄</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<form>
賬號:<input type="text" v-model="username" @blur="checkUsername()">
<span style="color:red">{{username_msg}}</span><br>
密碼:<input type="password" v-model="pwd" @blur="checkPwd()">
<span style="color:red">{{pwd_msg}}</span><br>
<input type="button" value="登錄" @click="login()">
</form>
</div>
<script>
const vueApp = Vue.createApp({
data(){
return {
username:"",
pwd:"",
username_msg:"",
pwd_msg:"",
username_flag:false,
pwd_flag:false
}
},
methods:{
checkUsername(){
if (this.username == "") {
this.username_msg = "賬號不能為空";
this.username_flag = false;
} else if (this.username.length < 6) {
this.username_msg = "賬號至少6個(gè)字符";
this.username_flag = false;
} else {
axios({
method:"get",
url:"http://localhost:8888/day10_war_exploded/managerServlet?flag=checkUsername&username="+this.username
}).then(resp => {
if (resp.data) {
this.username_msg = "該賬號未注冊,請先注冊";
this.username_flag = false;
} else {
this.username_msg = "";
this.username_flag = true;
}
});
}
},
checkPwd(){
if (this.pwd == "") {
this.pwd_msg = "密碼不能為空";
this.pwd_flag = false;
} else if (this.pwd.length < 8) {
this.pwd_msg = "密碼至少8個(gè)字符";
this.pwd_flag = false;
} else {
this.pwd_msg = "";
this.pwd_flag = true;
}
},
login(){
if (this.username_flag && this.pwd_flag) {
let params = new URLSearchParams();
params.append("flag","login");
params.append("username",this.username);
params.append("pwd",this.pwd);
axios({
method:"post",
url:"http://localhost:8888/day10_war_exploded/managerServlet",
data:params
}).then(resp => {
if (resp.data) {
alert("登錄成功");
window.location.href = "index.html";
} else {
alert("密碼有誤,請查證后再登錄");
}
});
} else {
alert("請認(rèn)真填寫數(shù)據(jù)");
}
}
}
});
vueApp.mount("#app");
</script>
</body>
</html>
3.學(xué)生信息展示
(1) studentInfo.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="js/vue.global.js"></script>
<script src="js/axios.min.js"></script>
</head>
<body>
<div id="app">
<table cellspacing="0" cellpadding="0" border="1" width="500" align="center">
<tr>
<th>學(xué)號</th>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
<th>郵箱</th>
<th>頭像</th>
</tr>
<tr v-for="stu in stus">
<td>{{stu.sid}}</td>
<td>{{stu.sname}}</td>
<td>{{stu.sage}}</td>
<td>{{stu.sgender}}</td>
<td>{{stu.semail}}</td>
<td>
<img :src="'http://localhost:8888/sms_pic/student/'+stu.sphoto" width="50">
</td>
</tr>
</table>
<div>
<a href="javascript:void(0)" @click="getStudentByPage(1)">首頁</a>
<a href="javascript:void(0)" @click="getStudentByPage(prevPage)">上一頁</a>
{{page}}/{{countPages}}
<a href="javascript:void(0)" @click="getStudentByPage(nextPage)">下一頁</a>
<a href="javascript:void(0)" @click="getStudentByPage(countPages)">尾頁</a>
</div>
</div>
<script>
const vueApp = Vue.createApp({
data:function(){
return {
stus:"",
page:"",
countPages:"",
prevPage:"",
nextPage:""
}
},
methods:{
getStudentByPage(p){
let params = new URLSearchParams();
params.append("flag","getStudentByPage");
params.append("page",p);
axios({
method:"post",
url:"http://localhost:8888/day10_war_exploded/studentServlet",
data:params
}).then(resp => {
this.stus = resp.data.list;
this.page = resp.data.page;
this.countPages = resp.data.countPages;
this.prevPage = resp.data.prevPage;
this.nextPage = resp.data.nextPage;
});
}
},
created:function(){
this.getStudentByPage(1);
}
});
vueApp.mount("#app");
</script>
</body>
</html>
(2) PageUtil.java-分頁代碼
package com.etime.util;
import java.util.List;
public class PageUtil {
private int page; //當(dāng)前頁頁碼
private int rows; //每頁顯示條數(shù)
private int index; //偏移量
private int countRows; //總條數(shù)
private int countPages; //總頁數(shù)
private int prevPage; //當(dāng)前頁的上一頁頁碼
private int nextPage; //當(dāng)前頁的下一頁頁碼
private List list; //當(dāng)前頁的數(shù)據(jù)
public PageUtil(String page,int rows,int countRows){
init_page(page);
this.rows = rows;
init_index();
this.countRows = countRows;
init_countPages();
init_prevPage();
init_nextPage();
}
private void init_page(String page){
if (page == null || "".equals(page)) {
this.page = 1;
} else {
this.page = Integer.parseInt(page);
}
}
private void init_index(){
this.index = (this.page - 1) * this.rows;
}
private void init_countPages(){
int mod = this.countRows % this.rows;
if (mod == 0) {
this.countPages = this.countRows / this.rows;
} else {
this.countPages = this.countRows / this.rows + 1;
}
}
private void init_prevPage(){
if (this.page == 1) {
this.prevPage = 1;
} else {
this.prevPage = this.page - 1;
}
}
private void init_nextPage(){
if (this.page == this.countPages) {
this.nextPage = this.countPages;
} else {
this.nextPage = this.page + 1;
}
}
public int getPage() {
return page;
}
public int getRows() {
return rows;
}
public int getIndex() {
return index;
}
public int getCountRows() {
return countRows;
}
public int getCountPages() {
return countPages;
}
public int getPrevPage() {
return prevPage;
}
public int getNextPage() {
return nextPage;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
}
(3)StudentServlet.java
protected void getStudentByPage(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//分頁數(shù)據(jù)查詢
String page = req.getParameter("page");
int rows = 10;
int countRows = studentService.getCountRows();
PageUtil pageUtil = new PageUtil(page, rows, countRows);
List<Student> list = studentService.getStudentByPage(pageUtil);
pageUtil.setList(list);
ObjectMapper mapper = new ObjectMapper();
String res = mapper.writeValueAsString(pageUtil);
PrintWriter out = resp.getWriter();
out.print(res);
out.close();
}
(3)StudentServlet.java
protected void getStudentByPage(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//分頁數(shù)據(jù)查詢
String page = req.getParameter("page");
int rows = 10;
int countRows = studentService.getCountRows();
PageUtil pageUtil = new PageUtil(page, rows, countRows);
List<Student> list = studentService.getStudentByPage(pageUtil);
pageUtil.setList(list);
ObjectMapper mapper = new ObjectMapper();
String res = mapper.writeValueAsString(pageUtil);
PrintWriter out = resp.getWriter();
out.print(res);
out.close();
}
到了這里,關(guān)于Vue的Ajax請求-axios、前后端分離練習(xí)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!