ajax封装、axios与vue的使用demo
程序员文章站
2022-07-02 12:24:20
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ajax封装</title>
</head>
<body>
<script>
function ajax(options){
var xhr=new XMLHttpRequest();
var defaults={
type:'',
url:'',
data:{},
success: function () {},
error: function () {}
}
//把options付给defaults
Object.assign(defaults,options);
//发送的数据
var params='';
for(var attr in options.data){
params=params+=attr+'='+options.data[attr]+'&';
}
//将参数最后面的&给去掉
params=params.substr(0,params.length-1);
//封装get请求
if(defaults.type=='get'){
defaults.url=defaults.url+'?'+params;
console.log(defaults.url);
xhr.open(defaults.type,defaults.url);
xhr.send();
};
if(defaults.type=='post'){
xhr.open(defaults.type,defaults.url);
//console.log(defaults.url);
//console.log(typeof(defaults.data)=='string');
//设置格式
if(typeof(defaults.data)=='string'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send(defaults.data);
}else{
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(defaults.data));
};
}
xhr.onload=function(){
defaults.success(xhr.responseText);
}
}
ajax({
type:'post',
url:"http://localhost:5000/post",
data:"name:'zhangsan',age:10",
success:function(response){
console.log('后端返回来的数据:'+response);
}
})
</script>
</body>
</html>
axios和vue的引用
<!-- 官网提供的 axios 在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
axios的小demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>axios-vue</title>
<!-- 官网提供的 axios 在线地址 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="获取笑话" @click="getJoke"/>
<h3>{{smile}}</h3>
</div>
<script>
var app=new Vue({
el:"#app",
data:{
smile:"很好笑的笑话"
},
methods:{
getJoke:function(){
var that=this;//获取axios方法里面的值
axios.get("https://autumnfish.cn/api/joke").then(function(respon){
console.log(respon.data);
console.log(that.smile);
that.smile=respon.data;
},function(error){
console.log(error);
})
}
}
})
</script>
</body>
</html>