Day2.9 Vue中发ajax请求

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>第三方包vue-resource实现get,post,jsonp请求</title>
<script src="../lib/js/vue.js"></script>
<!-- vue-resource.js依赖于vue,先vue.js后vue-resource.js -->
<script src="https://cdn.bootcss.com/vue-resource/1.5.1/vue-resource.js"></script>
</head>
<body>
<div id="app">
<input type="button" value="get请求" @click="getInfo">
<input type="button" value="post请求" @click="postInfo">
<input type="button" value="jsonp请求" @click="jsonpInfo">
</div>
<script>
const vm = new Vue({
el:'#app',
data:{
},
methods:{
getInfo(){ //发起get请求
// 当发起get请求之后,通过.then 来设置成功的回调函数
this.$http.get('请求路径').then(function (result) {
// 通过 result.body 拿到服务器返回的成功的数据
console.log(result.body)
})
},
postInfo(){ //发起post请求
// 手动发起的 post 请求,默认没有表单格式,所以有的服务器处理不了
// 通过 post 方法的第三个参数:{emulateJSON:true} 设置 提交的内容类型 为 普通表单数据格式
this.$http.post('请求路径',{},{emulateJSON:true}).then(result =>{
console.log(result.body)
})
},
jsonpInfo(){ //发起jsonp请求
this.$http.jsonp('请求路径').then(result =>{
console.log(result.body)
})
}
}
})
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/zhaohui-116/p/12007961.html