vue進(jìn)行post和get請求實(shí)例講解
使用axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
一、基本使用方法
1、get請求
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
?.then(function (response) {
? console.log(response);
?})
?.catch(function (error) {
? console.log(error);
?});
?
// Optionally the request above could also be done as
axios.get('/user', {
? params: {
? ?ID: 12345
? }
?})
?.then(function (response) {
? console.log(response);
?})
?.catch(function (error) {
? console.log(error);
?});2.Post請求
axios.post('/user', {
?firstName: 'Fred',
?lastName: 'Flintstone'
})
.then(function (response) {
?console.log(response);
})
.catch(function (error) {
?console.log(error);
});簡單示例:
// 在進(jìn)行 post 和 get 請求的時候,使用 axios 進(jìn)行訪問
// 進(jìn)行 get 請求
axios.get(url).then(function (response){
? ? console.log(response);
}).catch(function(error){
? ? console.log(error);
});
// 進(jìn)行post 請求 ? ? ? ? ? ?
axios.post(url,{firstName:'Fred',lastName:'Flintstone'}).then(function (response) {
? ? console.log(response);
}).catch(function (error) {
? ? console.log(error);
});這樣發(fā)送請求,雖然是可以發(fā)送,但是攜帶的參數(shù),是一個json字符串,會出現(xiàn)問題。所以我們在用post發(fā)送請求的時候,需要這樣:
axios({ ?
? ? method:'post', ?
? ? url:url, ?
? ? data:{title:this.title,content:this.content}, ?
? ? headers:{'Content-Type': 'application/x-www-form-urlencoded'}, ?
? ? transformRequest: function(obj) { ?
? ? ? ? var str = []; ?
? ? ? ? for(var p in obj){ ?
? ? ? ? ? ? str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); ?
? ? ? ? } ?
? ? ? ? return str.join("&"); ?
? ? } ?
}).then((res)=>{
? ? console.log(res.data);
});
上面這種只能提交一些簡單的數(shù)據(jù),對于復(fù)雜的數(shù)據(jù),可以考慮使用 QS 對數(shù)據(jù)進(jìn)行處理。
使用方法,如果找不到QS文件,可以只用 npm 安裝:
npm install qs

下載這個文件之后,使用 script 標(biāo)簽正常引入即可。
使用方法:
var formData = Qs.stringify({imgIds: [48,49],});
axios.post(url,Qs.stringify(this.formData)).then(function (response) {
? ? console.log(response);
}).catch(function (error) {
? ? console.log(error);
});或者是:
axios({
? ? method: 'post',
? ? url:url,
? ? data:Qs.stringify(this.formData),
}).then((res)=>{
? ? console.log(res);
});到此這篇關(guān)于vue進(jìn)行post和get請求實(shí)例講解的文章就介紹到這了,更多相關(guān)vue進(jìn)行post和get請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue數(shù)據(jù)渲染出現(xiàn)閃爍問題
本篇文章主要介紹了vue數(shù)據(jù)渲染出現(xiàn)閃爍問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
cesium開發(fā)之如何在vue項目中使用cesium,使用離線地圖資源
這篇文章主要介紹了cesium開發(fā)之如何在vue項目中使用cesium,使用離線地圖資源問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
Vue組件Draggable實(shí)現(xiàn)拖拽功能
這篇文章主要為大家詳細(xì)介紹了Vue組件Draggable實(shí)現(xiàn)拖拽功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12

