Vue通过axios发送ajax请求

在Vue中是不支持发送ajax请求的,如果我们要在Vue中发送ajax请求,我们需借助第三方插件
常用发送ajax请求插件有两个 vue-resource和axios,Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。
1.axios
https://gitcode.net/mirrors/axios/axios
引入方式
npm方式: npm install axios
bower方式 bower install axios
yarn方式 yarn add axios
CDN方式
基本使用
发送简单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后面的匿名函数为请求成功的回调函数
打印结果如下
在这里插入图片描述
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);
				})
			}
		}
	})

2.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)
})

原文链接:https://blog.csdn.net/weixin_45143481/article/details/104860418

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值