Vue通过axios发送ajax请求基础演示

发布时间:2023-03-25 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue通过axios发送ajax请求基础演示脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

在Vue中是不支持发送ajax请求的,如果我们要在Vue中发送ajax请求,我们需借助第三方插件
常用发送ajax请求插件有两个 vue-resource和axios,Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。

axios项目https://github.com/axios/axios

axios引入方式

npm方式: npm install axios

bower方式 bower install axios

yarn方式 yarn add axios

CDN方式<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

axios基本使用

axios发送简单get请求

//1.php
<?php
echo 123;
//htML

 <div id='app'>
    	<input tyPE="button" @click='get' value='get' name="">
    	<input type="button" @click='post' value='post' name="">
    	<input type="button" @click='jsonp' value='jsonp' name="">
    </div>
//js
<script type="text/javascript">
	VAR vm = new Vue({
		el:'#app',
		methods:{
			get(){
				axios.get('1.php').then(res=>{
					console.LOG(res);
				})
			}
		}
	})
</script>

then后面的匿名函数为请求成功的回调函数

打印结果如下

在这里插入图片描述
&nbsp;

axios get传参

1.直接写在url后面

var vm = new Vue({
		el:'#app',
		methods:{
			get(){
				axios.get('1.php?id=1&name="测试"').then(res=>{
					console.log(res);
				})
			}
		}
	})

2.通过params参数

var vm = new Vue({
		el:'#app',
		methods:{
			get(){
				axios.get('1.php',{params:{
					id:1,
					name:'测试'
				}}).then(res=>{
					console.log(res);
				})
			}
		}
	})

axios发送post请求

axios({
	method: 'post',
	url: '1.php',
	params: {
	FirstName: 'Fred',
	lastName: 'Flintstone'
	},
    headers: {
			'Content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
	},
}).then(function(res){
		console.log(res)
	})

注意:直接使用axiox发送post请求时,会使后端接收不到数据

解决方法如下

一,在发送post请求时我们要手动设置请求头Content-Type:application/x-www-form-urlencoded并且我们将传递参数的属性data换成了params,使用data发送数据,后端接收不到
二,使用data发送数据时,我们可以在数据发送之前进行数据转换转换为key=value&key2=value2…的形式

axios({
	url: '1.php',
	method: 'post',
	data: {
			firstName: 'Fred',
			lastName: 'Flintstone'
	},
	//数据转换
	transformRequest:[data=>{
		let res = ''
		for (let ITem in data){
				res +=item + "="+data[item]+"&";
		}
		return res;
	 }],
				  
	headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		}
}).then(function(res){
		console.log(res)
})

以上就是Vue通过axios发送ajax请求基础演示的详细内容,更多关于Vue通过axios发送ajax请求的资料请关注脚本宝典其它相关文章

脚本宝典总结

以上是脚本宝典为你收集整理的Vue通过axios发送ajax请求基础演示全部内容,希望文章能够帮你解决Vue通过axios发送ajax请求基础演示所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。