最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Vue通過axios發(fā)送ajax請求基礎(chǔ)演示

 更新時間:2023年02月18日 13:45:04   作者:zihanzy  
這篇文章主要介紹了Vue通過axios發(fā)送ajax請求基礎(chǔ)演示,包括了axios發(fā)送簡單get請求,axios get傳參,axios發(fā)送post請求等基礎(chǔ)代碼演示需要的朋友可以參考下

在Vue中是不支持發(fā)送ajax請求的,如果我們要在Vue中發(fā)送ajax請求,我們需借助第三方插件
常用發(fā)送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發(fā)送簡單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后面的匿名函數(shù)為請求成功的回調(diào)函數(shù)

打印結(jié)果如下

在這里插入圖片描述
 

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參數(shù)

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

axios發(fā)送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發(fā)送post請求時,會使后端接收不到數(shù)據(jù)

解決方法如下

一,在發(fā)送post請求時我們要手動設(shè)置請求頭Content-Type:application/x-www-form-urlencoded并且我們將傳遞參數(shù)的屬性data換成了params,使用data發(fā)送數(shù)據(jù),后端接收不到
二,使用data發(fā)送數(shù)據(jù)時,我們可以在數(shù)據(jù)發(fā)送之前進行數(shù)據(jù)轉(zhuǎn)換轉(zhuǎn)換為key=value&key2=value2…的形式

axios({
	url: '1.php',
	method: 'post',
	data: {
			firstName: 'Fred',
			lastName: 'Flintstone'
	},
	//數(shù)據(jù)轉(zhuǎn)換
	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發(fā)送ajax請求基礎(chǔ)演示的詳細(xì)內(nèi)容,更多關(guān)于Vue通過axios發(fā)送ajax請求的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論

萍乡市| 嘉善县| 邵武市| 五家渠市| 昔阳县| 怀来县| 富裕县| 陆川县| 卢氏县| 奈曼旗| 安达市| 哈巴河县| 长岭县| 敦化市| 柳林县| 柘荣县| 永安市| 汉寿县| 宜兴市| 彭州市| 锡林浩特市| 社会| 长汀县| 长沙县| 雷州市| 右玉县| 松阳县| 丰宁| 多伦县| 南江县| 青海省| 二手房| 壶关县| 忻州市| 祁阳县| 启东市| 鄄城县| 清河县| 宜兰县| 会同县| 于田县|