Vue异步请求模块 axios的简单应用,总结都写在代码里
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<button class="get">get请求</button>
<button class="post">post请求</button>
</body>
<!-- 官网提供的 axios 在线 cdn -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
/*
接口1: 随即笑话
请求地址: https://autumnfish.cn/api/joke/list
请求方法: get
请求参数: num(笑话条数,数字)
响应内容: 随即笑话
*/
document.querySelector(".get").onclick = function() {
axios.get("https://autumnfish.cn/api/joke/list?num=6").then(function(response) {
console.log(response)
}, function(err){
console.log(err)
})
}
/*
接口2: 用户注册
请求地址: https://autumnfish.cn/api/user/reg
请求方法: post
请求参数: username(用户名, 字符串)
响应内容: 注册成功或者失败
*/
document.querySelector(".post").onclick= function(){
axios.post("https://autumnfish.cn/api/user/reg", {username: '孙下摆'}).then(function(response){
console.log(response)
}, function(err){
console.log(err)
})
}
</script>
<!-- axios基本使用总结:
本质上还是封装了 ajax 的功能
1. axios必须先导入才能使用
2. 使用 get 或 post 方法即可发送对应的请求,还有其他很多请求,官网有定义
get:
axios.get("url请求地址?key1=参数1&key2=参数2").then(function(respose){}, function(err){})
post:
axios.post("url请求地址", {文档定义参数名: "参数"}).then(function(respose){}, function(err){})
3.then方法中的回调函数会在请求成功或者失败的时候触发
then回调函数有两个,第一个是请求成功返回的信息,第二个是请求失败返回的错误信息
4.通过回调函数的形参可以获取响应的内容,或者错误信息
官网: http://axios-js.com/ -->
</html>