axios的两种用法
1.通过get方式获取数据
axios(options)参数是一个对象;
axios({ url: ' http://localhost/xxx.php ',
params:{
属性:属性值,
属性:属性值.......
}
}).then( res =>console.log(res) )
.catch(error => if(error) throw error)
axios的默认方式是get方式,所以method可以省略不写
2.通过post方法获取数据
axios(options)参数是一个对象;
var params = new URLSearchParams();
params.append( 属性,属性值 )
params.append( 属性,属性值 )
axios({url:'http://localhost/xxx.php',
method:'post',
headers: { //只对此模板有效
'Content-Type': 'application/x-www-form-urlencoded'
},
//传参
data:params;
}).then( res =>console.log(res) )
.catch(error =>{ if(error)=>throw error})
原生fetch()方法获取数据
get方式
fetch(option)
fetch({http://localhost/xxx.php?a=1&b=3})
.then(res => res.text())
//与axios不同的一点是 得到的数据需要转义
.then(data => console.log(data))
.catch(error => {
if (error) throw error
})
get方法传参的形式 很像form表单中通过get传递数据时,会在浏览器地址栏显示的形式一样。
post方法
fetch(url,{})
fetch('http://localhost/xxx.php',{
method: 'post',
headers: new Headers({ //解决跨域
'Content-Type': "application/x-www-form-urlencoded"
}),
body: new URLSearchParams([
['a', 1],
['b', 20]
]).toString()
}).then(res => res.text())
.then(data => console.log(data))
.catch(error => {
if (error) throw error
})
})