代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue--resouse的简单使用</title>
<script src="https://lib.baomitu.com/vue/2.6.10/vue.min.js"></script>
<!-- 注意:vue-resource 依赖于 Vue,所以先后顺序要注意 -->
<!-- this.$http.jsonp -->
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
</head>
<body>
<div id="app">
<input type="button" value="get请求" @click="doGet">
<input type="button" value="post请求" @click="doPost">
<input type="button" value="jsonp请求" @click="doJsonp">
<h2 v-text="json"></h2>
</div>
<script>
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
json:""
},
methods: {
doGet(){
// GET /Url
this.$http.get('./lib/data.json').then(response => {
//成功的回调
this.json=response.body
}, response => {
//失败的回调
this.json="请求失败"
});
},
doPost() {
// 发起 post 请求 application/x-wwww-form-urlencoded
// 手动发起的 Post 请求,默认没有表单格式,所以,有的服务器处理不了
// 通过 post 方法的第三个参数, { emulateJSON: true } 设置 提交的内容类型 为 普通表单数据格式
this.$http.post('./lib/data.json', {}, { emulateJSON: true }).then(result => {
this.json=result.body
})
},
doJsonp() { // 发起JSONP 请求
this.$http.jsonp('https://api.asilu.com/phone?phone=13666666666').then(result => {
this.json=result.body
})
}
}
});
</script>
</body>
</html>
效果图
get
post
jsonp