4. 通過axios實(shí)現(xiàn)數(shù)據(jù)請求
vue.js默認(rèn)沒有提供ajax功能的姥闪。
所以使用vue的時(shí)候漓踢,一般都會(huì)使用axios的插件來實(shí)現(xiàn)ajax與后端服務(wù)器的數(shù)據(jù)交互赖草。
注意滴某,axios本質(zhì)上就是javascript的ajax封裝,所以會(huì)被同源策略限制站宗。
下載地址:
https://unpkg.com/axios@0.18.0/dist/axios.js
https://unpkg.com/axios@0.18.0/dist/axios.min.js
axios提供發(fā)送請求的常用方法有兩個(gè):axios.get() 和 axios.post() 闸准。
增 post
刪 delete
改 put/patch
查 get
// 發(fā)送get請求
// 參數(shù)1: 必填,字符串梢灭,請求的數(shù)據(jù)接口的url地址夷家,例如請求地址:http://www.baidu.com?id=200
// 參數(shù)2:可選,json對象敏释,要提供給數(shù)據(jù)接口的參數(shù)
// 參數(shù)3:可選瘾英,json對象,請求頭信息
axios.get('服務(wù)器的資源地址',{ // http://www.baidu.com
params:{
參數(shù)名:'參數(shù)值', // id: 200,
}
}).then(function (response) { // 請求成功以后的回調(diào)函數(shù)
console.log("請求成功");
console.log(response.data); // 獲取服務(wù)端提供的數(shù)據(jù)
}).catch(function (error) { // 請求失敗以后的回調(diào)函數(shù)
console.log("請求失敗");
console.log(error.response); // 獲取錯(cuò)誤信息
});
// 發(fā)送post請求颂暇,參數(shù)和使用和axios.get()一樣。
// 參數(shù)1: 必填但惶,字符串耳鸯,請求的數(shù)據(jù)接口的url地址
// 參數(shù)2:必填,json對象膀曾,要提供給數(shù)據(jù)接口的參數(shù),如果沒有參數(shù)县爬,則必須使用{}
// 參數(shù)3:可選,json對象添谊,請求頭信息
axios.post('服務(wù)器的資源地址',{
username: 'xiaoming',
password: '123456'
},{
responseData:"json",
})
.then(function (response) { // 請求成功以后的回調(diào)函數(shù)
console.log(response);
})
.catch(function (error) { // 請求失敗以后的回調(diào)函數(shù)
console.log(error);
});
// b'firstName=Fred&lastName=Flintstone'
4.1 json
json是 JavaScript Object Notation 的首字母縮寫财喳,單詞的意思是javascript對象表示法,這里說的json指的是類似于javascript對象的一種數(shù)據(jù)格式。
json的作用:在不同的系統(tǒng)平臺耳高,或不同編程語言之間傳遞數(shù)據(jù)扎瓶。
4.1.1 json數(shù)據(jù)的語法
json數(shù)據(jù)對象類似于JavaScript中的對象,但是它的鍵對應(yīng)的值里面是沒有函數(shù)方法的泌枪,值可以是普通變量概荷,不支持undefined,值還可以是數(shù)組或者json對象碌燕。
// 原生的js的json對象
var obj = {
age:10,
sex: '女',
work:function(){
return "好好學(xué)習(xí)",
}
}
// json數(shù)據(jù)的對象格式,json數(shù)據(jù)格式,是沒有方法的,只有屬性:
{
"name":"tom",
"age":18
}
// json數(shù)據(jù)的數(shù)組格式:
["tom",18,"programmer"]
復(fù)雜的json格式數(shù)據(jù)可以包含對象和數(shù)組的寫法误证。
{
"name":"小明",
"age":200,
"is_delete": false,
"fav":["code","eat","swim","read"],
"son":{
"name":"小小明",
"age":100,
"lve":["code","eat"]
}
}
// 數(shù)組結(jié)構(gòu)也可以作為json傳輸數(shù)據(jù)。
json數(shù)據(jù)可以保存在.json文件中修壕,一般里面就只有一個(gè)json對象愈捅。
總結(jié):
1. json文件的后綴是.json
2. json文件一般保存一個(gè)單一的json數(shù)據(jù)
3. json數(shù)據(jù)的屬性不能是方法或者undefined,屬性值只能:數(shù)值[整數(shù),小數(shù),布爾值]慈鸠、字符串蓝谨、json和數(shù)組
4. json數(shù)據(jù)只使用雙引號、每一個(gè)屬性成員之間使用逗號隔開林束,并且最后一個(gè)成員沒有逗號像棘。
{
"name":"小明",
"age":200,
"fav":["code","eat","swim","read"],
"son":{
"name":"小小明",
"age":100
}
}
工具:postman可以用于測試開發(fā)的數(shù)據(jù)接口。
4.1.2 js中提供的json數(shù)據(jù)轉(zhuǎn)換方法
javascript提供了一個(gè)JSON對象來操作json數(shù)據(jù)的數(shù)據(jù)轉(zhuǎn)換.
方法 | 參數(shù) | 返回值 | 描述 |
---|---|---|---|
stringify | json對象 | 字符串 | json對象轉(zhuǎn)成字符串 |
parse | 字符串 | json對象 | 字符串格式的json數(shù)據(jù)轉(zhuǎn)成json對象 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// json語法
let humen = {
"username":"xiaohui",
"password":"1234567",
"age":20
};
console.log(humen);
console.log(typeof humen);
// JSON對象提供對json格式數(shù)據(jù)的轉(zhuǎn)換功能
// stringify(json對象) # 用于把json轉(zhuǎn)換成字符串
let result = JSON.stringify(humen);
console.log(result);
console.log(typeof result);
// parse(字符串類型的json數(shù)據(jù)) # 用于把字符串轉(zhuǎn)成json對象
let json_str = '{"password":"1123","age":20,"name":"xiaobai"}';
console.log(json_str)
console.log(typeof json_str)
let json_obj = JSON.parse(json_str);
console.log(json_obj);
console.log(typeof json_obj)
console.log(json_obj.age)
</script>
</body>
</html>
4.2 ajax
ajax壶冒,一般中文稱之為:"阿賈克斯"缕题,是英文 “Async Javascript And Xml”的簡寫,譯作:異步j(luò)s和xml數(shù)據(jù)傳輸數(shù)據(jù)胖腾。
ajax的作用: ajax可以讓js代替瀏覽器向后端程序發(fā)送http請求烟零,與后端通信,在用戶不知道的情況下操作數(shù)據(jù)和信息咸作,從而實(shí)現(xiàn)頁面局部刷新數(shù)據(jù)/無刷新更新數(shù)據(jù)锨阿。
所以開發(fā)中ajax是很常用的技術(shù),主要用于操作后端提供的數(shù)據(jù)接口
记罚,從而實(shí)現(xiàn)網(wǎng)站的前后端分離
先誉。
ajax技術(shù)的原理是實(shí)例化js的XMLHttpRequest對象,使用此對象提供的內(nèi)置方法就可以與后端進(jìn)行數(shù)據(jù)通信框舔。
4.2.1 數(shù)據(jù)接口
數(shù)據(jù)接口辩尊,也叫api接口,表示后端提供
操作數(shù)據(jù)/功能的url地址給客戶端使用说庭。
客戶端通過發(fā)起請求向服務(wù)端提供的url地址申請操作數(shù)據(jù)【操作一般:增刪查改】
同時(shí)在工作中然磷,大部分?jǐn)?shù)據(jù)接口都不是手寫,而是通過函數(shù)庫/框架來生成刊驴。
4.2.3 ajax的使用
ajax的使用必須與服務(wù)端程序配合使用姿搜,但是目前我們先學(xué)習(xí)ajax的使用寡润,所以暫時(shí)先不涉及到服務(wù)端python代碼的編寫。因此舅柜,我們可以使用別人寫好的數(shù)據(jù)接口進(jìn)行調(diào)用梭纹。
jQuery將ajax封裝成了一個(gè)函數(shù)$.ajax(),我們可以直接用這個(gè)函數(shù)來執(zhí)行ajax請求业踢。
編寫代碼獲取接口提供的數(shù)據(jù):
jQ版本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<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栗柒,提交數(shù)據(jù)的方式,默認(rèn)是'GET'知举,常用的還有'POST'
type: 'get',
dataType: 'json', // 返回的數(shù)據(jù)格式瞬沦,常用的有是'json','html',"jsonp"
data:{ // 設(shè)置發(fā)送給服務(wù)器的數(shù)據(jù),如果是get請求雇锡,也可以寫在url地址的?后面
"city":'北京'
}
})
.done(function(resp) { // 請求成功以后的操作
console.log(resp);
})
.fail(function(error) { // 請求失敗以后的操作
console.log(error);
});
});
})
</script>
</head>
<body>
<button id="btn">點(diǎn)擊獲取數(shù)據(jù)</button>
</body>
</html>
vue版本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<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">點(diǎn)擊獲取天氣</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)
});
// 上面的參數(shù)寫法,也可以是下面這種格式:
// axios.get("http://wthrcdn.etouch.cn/weather_mini",{
// // get請求的附帶參數(shù)
// params:{
// "city":"廣州",
// }
// }).then(response=>{
// console.log(response.data); // 獲取接口數(shù)據(jù)
// }).catch(error=>{
// console.log(error.response); // 獲取錯(cuò)誤信息
// })
}
}
})
</script>
</body>
</html>
4.2.4 同源策略
同源策略逛钻,是瀏覽器為了保護(hù)用戶信息安全的一種安全機(jī)制。所謂的同源就是指代通信的兩個(gè)地址(例如服務(wù)端接口地址與瀏覽器客戶端頁面地址)之間比較锰提,是否協(xié)議曙痘、域名(IP)和端口相同。不同源的客戶端腳本[javascript]在沒有明確授權(quán)的情況下立肘,沒有權(quán)限讀寫對方信息边坤。
ajax本質(zhì)上還是javascript,是運(yùn)行在瀏覽器中的腳本語言谅年,所以會(huì)被受到瀏覽器的同源策略所限制茧痒。
前端地址:http://www.old.cn/index.html
|
是否同源 | 原因 |
---|---|---|
http://www.old.cn/user/login.html |
是 | 協(xié)議、域名融蹂、端口相同 |
http://www.old.cn/about.html |
是 | 協(xié)議旺订、域名、端口相同 |
https://www.old.cn/user/login.html |
否 | 協(xié)議不同 ( https和http ) |
http:/www.old.cn:5000/user/login.html |
否 | 端口 不同( 5000和80) |
http://bbs.old.cn/user/login.html |
否 | 域名不同 ( bbs和www ) |
同源策略針對ajax的攔截超燃,代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
<script src="js/axios.js"></script>
</head>
<body>
<div id="app">
<button @click="get_music">點(diǎn)擊獲取天氣</button>
</div>
<script>
let vm = new Vue({
el:"#app",
data:{},
methods:{
get_music(){
axios.get("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=xxx")
.then(response=>{
console.log(response);
}).catch(error=>{
console.log(error.response)
});
}
}
})
</script>
</body>
</html>
上面代碼運(yùn)行錯(cuò)誤如下:
Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
上面錯(cuò)誤区拳,關(guān)鍵詞:Access-Control-Allow-Origin
只要出現(xiàn)這個(gè)關(guān)鍵詞,就是訪問受限意乓。出現(xiàn)同源策略的攔截問題樱调。
4.2.5 ajax跨域(跨源)方案之CORS
ajax跨域(跨源)方案:后端授權(quán)[CORS],jsonp届良,服務(wù)端代理
? CORS是一個(gè)W3C標(biāo)準(zhǔn)本涕,全稱是"跨域資源共享",它允許瀏覽器向跨源的后端服務(wù)器發(fā)出ajax請求伙窃,從而克服了AJAX只能同源使用的限制。
? 實(shí)現(xiàn)CORS主要依靠<mark>后端服務(wù)器中響應(yīng)數(shù)據(jù)中設(shè)置響應(yīng)頭信息Access-Control-Allow-Origin返回</mark>的样漆。
django的視圖
def post(request):
? response = new Response()
? response .headers["Access-Control-Allow-Origin"] = "http://localhost:63342"
? return response;
// 在響應(yīng)行信息里面設(shè)置以下內(nèi)容:
Access-Control-Allow-Origin: ajax所在的域名地址
Access-Control-Allow-Origin: www.oldboy.cn # 表示只允許www.oldboy.cn域名的客戶端的ajax跨域訪問
// * 表示任意源为障,表示允許任意源下的客戶端的ajax都可以訪問當(dāng)前服務(wù)端信息
Access-Control-Allow-Origin: *
總結(jié):
0. 同源策略:瀏覽器的一種保護(hù)用戶數(shù)據(jù)的一種安全機(jī)制。
瀏覽器會(huì)限制ajax不能跨源訪問其他源的數(shù)據(jù)地址。
同源:判斷兩個(gè)通信的地址之間鳍怨,是否協(xié)議呻右,域名[IP],端口一致鞋喇。
ajax: http://127.0.0.1/index.html
api數(shù)據(jù)接口: http://localhost/index
這兩個(gè)是同源么声滥?不是同源的。是否同源的判斷依據(jù)不會(huì)根據(jù)電腦來判斷侦香,而是通過協(xié)議落塑、域名、端口的字符串是否來判斷罐韩。
1. ajax默認(rèn)情況下會(huì)受到同源策略的影響憾赁,一旦受到影響會(huì)報(bào)錯(cuò)誤如下:
No 'Access-Control-Allow-Origin' header is present on the requested resource
2. 解決ajax只能同源訪問數(shù)據(jù)接口的方式:
1. CORS,跨域資源共享散吵,在服務(wù)端的響應(yīng)行中設(shè)置:
Access-Control-Allow-Origin: 允許訪問的域名地址
2. jsonp
3. 是否服務(wù)端代理
思路:通過python來請求對應(yīng)的服務(wù)器接口龙考,獲取到數(shù)據(jù)以后,