axios、链式语法、url路径传参的流程、动态新增的元素注册事件、 axios库发送普通键值对的参数URLSearchParams()
1.axiosaxios是什么 :一个js框架,用于发送ajax请求(底层使用XMLHttpRequest)get('url') : 写url和请求参数then(res=>{})//成功回调, 相当于以前jq的successcatch(err=>{})//失败回调,一般可以省略不写then(()=>{})//完成回调,表示请求完成,无论成功失败都会执行。一般可以省略不写axios
·
1.axios
axios是什么 :
一个js框架,用于发送ajax请求(底层使用XMLHttpRequest)
get('url') : 写url和请求参数
then(res=>{}) //成功回调, 相当于以前jq的success
catch(err=>{}) //失败回调, 一般可以省略不写
then(()=>{}) //完成回调, 表示请求完成,无论成功失败都会执行。一般可以省略不写
axios常用语法
//axios常用语法 :
axios({
method:'请求方法',
url:'请求路径',
params : { get参数 },
data : { post参数 }
}).then( res=>{} )
2.链式语法
1.链式语法 : 对象可以连续调用方法
axios.get().then().catch()
2.链式语法底层原理 : 在对象的方法中返回自身
return this
let obj = {
name:'张三',
age:20,
sex:'男'
}
//给对象添加方法
obj.setName = function(str){
this.name = str
return this
}
obj.setAge = function(num){
this.age = num
return this
}
obj.setSex = function(str){
this.sex = str
return this
}
//调用方法
obj
.setName('李四')
.setAge(22)
.setSex('女')
console.log( obj )
3.动态新增的元素注册事件
动态新增的元素,无法直接注册事件的。 解决方案有两种
1.最常用 : 事件委托技术
2.偶尔用 : 行内式js注册事件 (事件处理只有1行代码)
<div onclick=" 事件处理代码 "></div>
4.url路径传参的流程总结
A页面 跳转到 B页面
1 . 给按钮添加行内js跳转 (动态新增按钮不能直接获取,但是可以注册行内事件)
2 . 在url路径的后面拼接你的参数 ( 页面跳转只由路径决定, 参数影响跳转)
<button onclick=" location.href= ' url?id=参数值 ' "></button>
3 . 在B页面解析location.search参数
let id = location.search.split('=')[1]
当页面只能传一个参数时,会省略参数名,直接写参数值
url:`https://autumnfish.cn/fruitApi/fruit/${id}`
网络请求loading效果
loading原理 : gif动图
显示loading : 发送ajax之前
隐藏loading : 服务器响应之后
/* 服务器响应之后:隐藏遮罩层
发现问题: 如果网速过快,遮罩层一闪而过,用户体验不好
解决方案: 开启一个一次性定时器,让用户多看一会儿酷炫的gif动图
*/
setTimeout(function() {
cover.style.display = "none"
//2.4 渲染页面
renderData(res.data.data.heros)
}, 1000)
axios库发送 普通键值对的参数
const params = new URLSearchParams();
params.append('name', '小花');
params.append('age', '18');
axios.post('http://localhost:3000/post', params, {
headers: {"content-type":"application/x-www-form-urlencoded"}})
更多推荐
已为社区贡献1条内容
所有评论(0)