axios
https://www.kancloud.cn/yunye/axios/234845
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
{{user.username}} | {{user.birthday}}
<button type="button" @click="sendpost">发送post请求</button>
</div>
<script>
//vue实例的生命周期(created:vue实例创建完毕,monted:页面数据已经挂载好了)
let vm=new Vue({
el:"#app",
data:{
user:{}
},
created() {
//发送ajax请求
//ajax跨域访问(跨源访问)
//get请求
axios.get('http://localhost:8080/user/user/14')
.then(response => {
console.log(response);
this.user=response.data;
//reponse.data-->this.user
})
.catch(function (error) {
console.log(error);
});
},
methods:{
sendpost(){
//axios的post,自动把请求数据组装成json,请求的Content-Type: application/json;charset=UTF-8
axios.post('http://localhost:8080/param/test', {
stuid: 1,
stuname: 'haha',
birthday:'1997-09-07'
})
.then(response => {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
});
</script>
</body>
</html>
增添 文件预览
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<form id="myform" method="post" enctype="multipart/form-data">
<input type="text" name="username"/>
<input type="password" name="password"/>
<input type="date" name="birthday"/><br/>
<img :src="base64img" ><br/>
<input type="file" name="avatarfile"@change="preview(this)"/><br/>
<button type="button" @click="adduser">注册</button>
</form>
</div>
<script>
let vm=new Vue({
el:"#app",
data:{
base64img:''
},
methods:{
adduser(){
var fd=new FormData(document.getElementById("myform"));
axios.post('http://localhost:8080/user/users',fd)
.then(response=>{
console.log(response);
})
.catch(err=>{
console.log(err);
})
},
preview(){
var that=this;
var file=event.target.files[0];
var fr=new FileReader();
fr.readAsDataURL(file);
fr.onload=function(e){
console.log(this);
that.base64img=e.target.result;
}
}
}
});
</script>
</body>
</html>
网友评论