Vue 学习第二部
json数据的语法
ajax
- 数据接口
- ajax的使用
- 同源策略
- ajax跨域(跨源)方案之cors
组件化开发
- 组件[component]
- 默认组件
通过axios实现数据请求
json
json是 JavaScript ObjectNotation的字母缩写,意思是javascript对象表达法,这里说的json指的是类似与javascript对象的一种数据格式.
json的作用:在不同的系统平台,或不同编程语言之间传递数据
http://wthrcdn.etouch.cn/weather_mini?city=城市名称
音乐接口搜索
http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=歌曲标题
音乐信息接口
http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid=音乐ID
编写代码获取接口的数据:
jQ版本
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="js/jquery-1.12.4.js">script>
<script>
$(function(){
$("#btn").on("click",function(){
$.ajax({
// 后端程序的url地址
url: 'http://wthrcdn.etouch.cn/weather_mini',
// 也可以使用method,提交数据的方式,默认是'GET',常用的还有'POST'
type: 'get',
dataType: 'json', // 返回的数据格式,常用的有是'json','html',"jsonp"
data:{ // 设置发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
"city":'北京'
}
})
.done(function(resp) { // 请求成功以后的操作
console.log(resp);
})
.fail(function(error) { // 请求失败以后的操作
console.log(error);
});
});
})
script>
head>
<body>
<button id="btn">点击获取数据button>
body>
html>
vue版本
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="js/vue.js">script>
<script src="js/axios.js">script>
head>
<body>
<div id="app">
<input type="text" v-model="city">
<button @click="get_weather">点击获取天气button>
div>
<script>
let vm = new Vue({
el:"#app",
data:{
city:"",
},
methods:{
get_weather(){
// http://wthrcdn.etouch.cn/weather_mini?city=城市名称
axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
.then(response=>{
console.log(response);
}).catch(error=>{
console.log(error.response)
});
// 上面的参数写法,也可以是下面这种格式:
// axios.get("http://wthrcdn.etouch.cn/weather_mini",{
// // get请求的附带参数
// params:{
// "city":"广州",
// }
// }).then(response=>{
// console.log(response.data); // 获取接口数据
// }).catch(error=>{
// console.log(error.response); // 获取错误信息
// })
}
}
})
script>
body>
html>