1.原生XMLHTTPREQUEST:這里不做解釋
2.window下的fetch(基于promise)
它響應(yīng)里有個json()方法,這也是個promise,所以也得使用.then。調(diào)用這個方法就可以得到請求的東西了。
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json))
3.vue-resourse(已經(jīng)停更)
引入CDN或者npm后,會在vue的實例上多一個$http的對象,用于ajax請求, 聽說VUE不更新這個東西了。
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,如果你習慣用vue-resourse:
Vue.prototype.$http = axios;
this.$http.get(url)
將其綁定在Vue實例原型上即可使用。
axios配置路由攔截:
ajax.interceptors.request.use() 與ajax.interceptors.response.use()
// 使用axios.create創(chuàng)建一個axios實例
const ajax = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
// 攔截器,攔截請求, 只要一有請求,就會執(zhí)行use里的方法, config就是請求的參數(shù)
ajax.interceptors.request.use((config) => {
// 可以在這里更改請求參數(shù),一般用于獲取web本地存儲的用戶token
config.headers['xxx-token'] = 'adsfqsaddggag'; //headers、body都行
vm.isLoading = true; //v-if來判斷提示加載中
return config;
});
// 攔截器,攔截響應(yīng),只要一有ajax數(shù)據(jù)返回,就會執(zhí)行use里的方法
ajax.interceptors.response.use((resp) => {
console.log('xxxx', resp)
// 在這里可以統(tǒng)一處理數(shù)據(jù)異常,但是前提是:后端數(shù)據(jù)足夠規(guī)范?。。?!
vm.isLoading = false;
if (resp.status === 200) {
return resp.data //到時候請求的時候,直接拿到data(不含status那些)
} else {
alert('出錯了!')
}
});
// 把ajax賦值給Vue.prototype.$http
//這樣在vue的實例里就可以通過this.$http來調(diào)用ajax
Vue.prototype.$http = ajax;
5.jQuery的ajax:
引入jquery,ajax有請求類型type配置,默認為GET。
$.ajax({
url: 'https://jsonplaceholder.typicode.com/todos/1',
type: "GET",
success: function(resp) {
console.log(resp)
}
})
jQuery的路由攔截配置:
$.ajaxSetup({
beforeSend: function() {
console.log('開始請求')
$('.loading').show(); //提示加載中
},
complete: function() {
$('.loading').hide();
}
})