1其馏、首先引入axios.js庫(kù)
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2木柬、HTML
<button id="btnUpload">發(fā)起GET請(qǐng)求</button>
<button id="btnUpload2">發(fā)起POST請(qǐng)求</button>
<button id="btn1">直接使用axios發(fā)起GET請(qǐng)求</button>
<button id="btn2">直接使用axios發(fā)起POST請(qǐng)求</button>
3闸餐、JS
document.querySelector('#btnUpload').addEventListener('click',function() {
var url = 'http://www.liulongbin.top:3006/api/get'
var paramsObj = {name: 'zs',age: 3}
// axios.get(url,{要傳輸?shù)膶?duì)象}).then(回調(diào)函數(shù))
axios.get(url,{params: paramsObj}).then(function(res){
console.log(res.data);
})
})
document.querySelector('#btnUpload2').addEventListener('click',function(){
// 請(qǐng)求的URL地址
var url = 'http://www.liulongbin.top:3006/api/post'
// 要提交到服務(wù)器的數(shù)據(jù)
var dataObj = {address:'北京',location: '順義'}
// 調(diào)用axios.post()發(fā)起POST請(qǐng)求
axios.post(url,dataObj).then(function(res) {
console.log(res.data);
})
})
document.querySelector('#btn1').addEventListener('click',function(){
// 請(qǐng)求的URL地址
var url = 'http://www.liulongbin.top:3006/api/get'
// 要提交到服務(wù)器的數(shù)據(jù)
var paramsData = {name:'鋼鐵俠',age: '35'}
axios({
method: 'GET',
url: url,
params: paramsData
}).then(function(res){
console.log(res.data);
})
})
document.querySelector('#btn2').addEventListener('click',function(){
axios({
method: 'POST',
url: 'http://www.liulongbin.top:3006/api/post',
data: {bookname:'大灰狼啃小紅',price: '88'}
}).then(function(res){
console.log(res.data);
})
})