<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Title</title>
<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<button id="getData">JQ-AJAX获取数据</button>
<button @click="getAxios">Vue获取数据</button>
</div>
<script>
new Vue({
el:"#app",
methods:{
//使用Vue中的axios获取数据
getAxios:function(){
axios.get('http://jsonplaceholder.typicode.com/users', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log("Vue获取的数据");
console.log(response.data);
})
.catch(function (error) {
console.log(error);
})
}
}
})
//使用
// $("#getData").click(function(){ //ES6之前写法
$("#getData").click( () =>{ //ES6写法
$.get("http://jsonplaceholder.typicode.com/users",function(src){
console.log("JQ-AJAX获取的数据")
console.log(src)
})
})
</script>
</body>
</html>
在Vue cli 中使用axios
//main.js中的axios配置
//使用Vue - Axios 第 1 步 引入数据请求(当然,要先安装一个axios : npm install --save-dev axios)
import Axios from 'axios'
//使用Vue - Axios 第 2 步 将Axios挂载到原型上
Vue.prototype.$axios = Axios;
//使用Vue - Axios 第 3 步 设置默认请求头
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.config.productionTip = false; //设置为 false 以阻止 vue 在启动时生成生产提示。
//添加请求拦截器, 当使用post请求时使用
Axios.interceptors.request.use(
function(config){
if(config.method == "post"){
config.data = qs.stringify(config.data)
}else{
return config;
}},
function(error){
//返回错误的请求
return Promise.reject(error);
}
);
Axios.interceptors.response.use(
function(response){
return response;
},
//返回错误的请求
function(error){
return Promise.reject(error);
}
)
使用axios
<script>
export default {
name: 'layout',
data () {
return {
}
},
created(){
this.$axios.get("http://jsonplaceholder.typicode.com/users",
).then(function (response) {
console.log("Vue获取的数据");
console.log(response.data);
}).catch(function (error) {
console.log(error);
})
}
}
</script>