1.原生XMLHTTPREQUEST:這里不做解釋
2.window下的fetch(基于promise)
它響應(yīng)里有個(gè)json()方法冠跷,這也是個(gè)promise南誊,所以也得使用.then。調(diào)用這個(gè)方法就可以得到請(qǐng)求的東西了蜜托。
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
3.vue-resourse(已經(jīng)停更)
引入CDN或者npm后抄囚,會(huì)在vue的實(shí)例上多一個(gè)$http的對(duì)象,用于ajax請(qǐng)求, 聽說VUE不更新這個(gè)東西了盗冷。
this.$http.get('https://jsonplaceholder.typicode.com/todos/1')
.then(resp => {
console.log(resp);
return resp.json()
})
.then(res => {
console.log(res)
})
4.axios(most popular)
安裝axios或者引入CDN怠苔,也是基于promise,如果你習(xí)慣用vue-resourse:
Vue.prototype.$http = axios;
this.$http.get(url)
將其綁定在Vue實(shí)例原型上即可使用仪糖。
axios配置路由攔截:
ajax.interceptors.request.use() 與ajax.interceptors.response.use()
// 使用axios.create創(chuàng)建一個(gè)axios實(shí)例
const ajax = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
// 攔截器柑司,攔截請(qǐng)求, 只要一有請(qǐng)求迫肖,就會(huì)執(zhí)行use里的方法, config就是請(qǐng)求的參數(shù)
ajax.interceptors.request.use((config) => {
// 可以在這里更改請(qǐng)求參數(shù),一般用于獲取web本地存儲(chǔ)的用戶token
config.headers['xxx-token'] = 'adsfqsaddggag'; //headers、body都行
vm.isLoading = true; //v-if來判斷提示加載中
return config;
});
// 攔截器攒驰,攔截響應(yīng)蟆湖,只要一有ajax數(shù)據(jù)返回,就會(huì)執(zhí)行use里的方法
ajax.interceptors.response.use((resp) => {
console.log('xxxx', resp)
// 在這里可以統(tǒng)一處理數(shù)據(jù)異常玻粪,但是前提是:后端數(shù)據(jù)足夠規(guī)范S缃颉!>⑹摇伦仍!
vm.isLoading = false;
if (resp.status === 200) {
return resp.data //到時(shí)候請(qǐng)求的時(shí)候,直接拿到data(不含status那些)
} else {
alert('出錯(cuò)了很洋!')
}
});
// 把a(bǔ)jax賦值給Vue.prototype.$http
//這樣在vue的實(shí)例里就可以通過this.$http來調(diào)用ajax
Vue.prototype.$http = ajax;
5.jQuery的ajax:
引入jquery,ajax有請(qǐng)求類型type配置充蓝,默認(rèn)為GET。
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
type: "GET",
success: function(resp) {
console.log(resp)
}
})
jQuery的路由攔截配置:
$.ajaxSetup({
beforeSend: function() {
console.log('開始請(qǐng)求')
$('.loading').show(); //提示加載中
},
complete: function() {
$('.loading').hide();
}
})