注意:get请求方式的请求参数如果要封装成对象传递过去,那么需要将请求参数对象再次封装,格式要求为:{params:我们的请求参数对象},例如:{params:this.user}
底层原理:axios底层会获取get方法参数二中对象的params属性值,将属性值中的对象转换成name=value&name=value&...格式的参数拼接到url地址后发送给服务器
<body>
<div id="div">
<input type="button" value="发送get请求方式1" @click="doGet1()">
<input type="button" value="发送get请求方式2" @click="doGet2()">
<input type="button" value="发送post请求方式1" @click="doPost1()">
<input type="button" value="发送post请求方式2" @click="doPost2()">
</div>
<script>
new Vue({
el:"#div",
data:{
user:{
username:"rose",
password:123
}
},
methods:{
//<input type="button" value="发送get请求方式1" @click="doGet1()">
doGet1(){
axios.get("ajaxServlet?username=jack&password=123456").then((resp)=>{
//结果:{data: "hello jack", status: 200, statusText: "", headers: {…}, config: {…}, …}
console.log(resp);
//获取响应回来的数据
console.log(resp.data);
}).catch((error)=>{
//信息红色字体展示
console.error(error);
});
},
//<input type="button" value="发送get请求方式2" @click="doGet2()">
//底层原理:axios底层会获取get方法参数二中对象的params属性值,将属性值中的对象转换成name=value&name=value&...格式的参数拼接到url地址后发送给服务器
doGet2(){
axios.get("ajaxServlet",{params:this.user}).then((resp)=>{
//结果:{data: "hello rose", status: 200, statusText: "", headers: {…}, config: {…}, …}
console.log(resp);
//获取响应回来的数据
console.log(resp.data);
}).catch((error)=>{
//信息红色字体展示
console.error(error);
});
},
}
});
</script>
//实际传递的参数格式: 'username=tom&password=20'
//请求参数username=tom ,这种方式发送过去的数据是name=value形式,可以直接使用BeanUtils封装。
axios.post("ajaxServlet","username=tom&password=20").then(function (resp) {
//处理成功的响应数据
console.log(resp);
console.log(resp.data); //hello
}).catch(function (data) {
//处理异常
});
doGet2(){
axios.get("ajaxServlet",{params:this.user}).then((resp)=>{
//结果:{data: "hello rose", status: 200, statusText: "", headers: {…}, config: {…}, …}
console.log(resp);
//获取响应回来的数据
console.log(resp.data);
}).catch((error)=>{
//信息红色字体展示
console.error(error);
});
},
//底层原理:axios底层会将post方法参数二中的对象转换成json字符串(springboot中就导入fastjson 直接使用你面方法jsonToString方法,也可以使用ObjectMapper mapper=new ObjectMapper() :mapper.readValue(request.getReader(),User.class)
),然后通过请求体发送给服务器
//实际发送过去的参数:{"username":"rose","password":123}
axios.post("ajaxServlet",this.user).then(function (resp) {
//处理成功的响应数据
ole.log(resp.data); //hello tom
}).catch(function (data) {
//处理异常
});