威海建设集团网站首页重庆seo技术教程
什么是Ajax:从服务器端动态获取数据并加载
如何发送ajax异步请求?使用AXIOS!! 对原生的ajax进行了封装
代码示例:
<body><input type="button" value="获取数据get" id="btnGet"><input type="button" value="操作数据post" id="btnPost"><!-- 引入axios --><script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script><script>// 发送get请求document.querySelector('#btnGet').addEventListener('click', function() {// 基于axios发起异步请求console.log('发送get请求');axios({method: 'get',url:'https://mock.apifox.cn/m1/3083103-0-default/emps/list'}).then(function(response){ // 成功回调console.log(response.data);}).catch(function(error){ // 失败回调console.log(error);});});// 发送post请求document.querySelector('#btnPost').addEventListener('click', function() {axios({method: 'post',url: '-',// 传入请求参数data:{}}).then(function(result){console.log(result.data);}).catch(function(error){console.log(error);})});</script>
</body>
document.querySelector("#btnGet2").addEventListener("click", function () {// 推荐的别名axios.get('https://mock.apifox.cn/m1/3083103-0-default/emps/list').then(function (response) {console.log(response.data);}).catch(function (error) {console.log(error);});});document.querySelector("#btnPost2").addEventListener("click", function(){// 推荐的别名axios.post('-').then(function(result){console.log(result.data);}).catch(function (error) {console.log(error);});});
现在我们成功使用异步请求得到了数据,但是网页刷新后并没有自动请求数据,如何做到在页面加载完后自动发起请求呢
要想完成这个操作,我们必须了解vue的生命周期
例:
// 声明钩子方法,在组件渲染完成后执行mounted(){// 调用search方法,获取员工列表数据this.search();}
end
致谢:本文参考黑马程序员的视频,本人也看过很多黑马程序员的视频,给我带来非常大的帮助。
https://www.bilibili.com/video/BV1yGydYEE3H/?vd_source=1b8f9bfb1d0891faf1c70d7678ae56db