推荐使用 Axios
- Axios 是专注于网络数据请求的库。
- 相比于原生的 XMLHttpRequest 对象,axios 简单易用。
- 相比于 jQuery,axios 更加轻量化,只专注于网络数据请求。
传统的Ajax (XHR)
基本使用步骤
创建 xhr
对象
调用 xhr.open()
函数
- (POST 请求)设置
Content-Type
属性(固定写法)
调用 xhr.send()
函数
监听 xhr.onreadystatechange
事件
GET请求
const xhr = new XMLHttpRequest()
xhr.open('GET','https://www.baidu.com/api?id=1&&page=2')
xhr.send()
xhr.onreadystatechange = function() { if(xhr.readyState === 4 && xhr.status === 200){ console.log(xhr.responeseText) } }
|
POST请求
const xhr = new XMLHttpRequest()
xhr.open('POST','https://www.baidu.com/api')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('id=1&author=fantasy&page=2) // 监听发起请求后的事件,onreadystatechange xhr.onreadystatechange = function() { // 监听 // 请求对象的请求状态 readyState // 服务器响应状态 status if(xhr.readyState === 4 && xhr.status === 200){ // responeseText响应回来的数据 console.log(xhr.responeseText) } }
|
XMLHttpRequest 对象的 readyState
属性,用来表示当前 Ajax 请求所处的状态。每个 Ajax 请求必然处于以下状态中的一个:
值 | 状态 | 描述 |
---|
0 | UNSENT | XMLHttpRequest 对象已被创建,但尚未调用 open方法。 |
1 | OPENED | open() 方法已经被调用。 |
2 | HEADERS_RECEIVED | send() 方法已经被调用,响应头也已经被接收。 |
3 | LOADING | 数据接收中,此时 response 属性中已经包含部分数据。 |
4 | DONE | Ajax 请求完成,这意味着数据传输已经彻底完成或失败。 |
设置 HTTP 请求时限
xhr.timeout = 3000 xhr.ontimeout = function(event){ alert('请求超时!') }
|
设置 http 请求时限,3000毫秒,超时执行 ontimeout 的回调函数
基本使用
const fd = new FormDate()
fd.append('id','12') fd.append('name','fantasy')
xhr.send(fd)
|
获取网页 dom 表单的值
const form = document.querySelector('#form')
form.addEventListener('submit', function(e) { e.preventDefault() const fd = new FormData(form) xhr.send(fd) }
|
上传文件
var fd = new FormData()
fd.append('avatar', files[0])
xhr.send(fd)
|
监听 xhr.upload.onprogress 文件的上传进度
xhr.upload.onprogress = function(e) { if (e.lengthComputable) { const percentComplete = Math.ceil((e.loaded / e.total) * 100) } }
|
监听 xhr.upload.onload 文件上传完成
xhr.upload.onload = function() { $('#percent') .removeClass() .addClass('progress-bar progress-bar-success') }
|
jQuery-Ajax
浏览器中提供的 XMLHttpRequest 用法比较复杂,所以 jQuery 对 XMLHttpRequest 进行了封装,提供了一系列 Ajax 相关的函数,极大地降低了 Ajax 的使用难度。
常用方式
$.get()
$.get(url,[data],[callback])
|
参数名 | 参数类型 | 是否必选 | 说明 |
---|
url | string | 是 | 请求的地址 |
data | object | 否 | 请求传递的参数 |
callback | function | 否 | 请求成功的回调函数 |
$.get('http://www.badui/api',{id:1,name:'fantasy'}, function(res) { console.log(res) })
|
$.post()
$.post(url,[data],[callback])
|
参数名 | 参数类型 | 是否必选 | 说明 |
---|
url | string | 是 | 请求的地址 |
data | object | 否 | 请求传递的参数 |
callback | function | 否 | 请求成功的回调函数 |
$.post('http://www.badui/api',{id:1,name:'fantasy'}, function(res) { console.log(res) })
|
$.ajax()
$.ajax({ type: '', url: '', data: { }, success: function(res) { } })
|
$.ajax({ type: 'get', url: 'http://www.badui/api', data: {id:1,name:'fantasy' }, success: function(res) { } })
|
FormDate 对象管理表单数据也适合 jQuery-Ajax
因为 FormDate 是 HTML5 新增的一个 对象,可以模拟表单操作
用法大致相同
拼接请求的根路径
建议新建 baseAPI.js
$.ajaxPrefilter(function(options) { options.url = 'http://ajax.frontend.itheima.net' + options.url })
|
if (options.url.indexOf('/my/') !== -1) { options.headers = { Authorization: localStorage.getItem('token') || '' } }
options.complete = function(res) { if (res.responseJSON.status === 1 && res.responseJSON.message === '身份认证失败!') { localStorage.removeItem('token') location.href = '/login.html' } }
|
Axios
axios.get
axios.get('url',{params:{ 参数 } } ).then(callback)
|
axios.get('url', { params :{ id: 1, name:'fantasy' } }).then(res => { consloe.log(res.data) })
|
参数名 | 参数类型 | 是否必选 | 说明 |
---|
url | string | 是 | 请求的地址 |
params | object | 否 | 请求传递的参数 |
callback | function | 否 | 请求成功的回调函数 |
axios.post
axios.post('url',{ 参数 } ).then(callback)
|
axios.post('url', { id:1, name:'fantasy' }).then(res => { consloe.log(res.data) })
|
axios
axios({
method/type:'请求类型', url:'请求地址', data:{ post 数据 }, params:{ get 参数} }).then(callback)
|
axios({ method:'get', url:'url', params:{id:1,name:'fantasy'} }).then(res => { consloe.log(res.data) })
|
配合 async / await 使用
axios返回的数据是一个Promise实例对象,用 .then()取到正确的数据
- async 关键字用于函数上(async函数的返回值是Promise实例对象)
- await 关键字用于 async 函数当中(await可以得到异步的结果)
document.querySelector('#btnPost').addEventListener('click', async function () { const { data: res } = await axios({ method: 'POST', url: '/api/post', data: { name: 'fantasy', id: 1 } })
console.log(res) })
|
vue 2.x 全局配置 axios
优点:每个组件可以通过 this.$http.get
直接发起请求,无需再导入 axios
;若根路径发生改变,只需修改 axios.defaults.baseURL
,有利于代码维护。
axios.defaults.baseURL = 'http://api.com'
Vue.prototype.$http = aixos
|
缺点:无法实现 API
的复用。即多个组件需要对同一个接口发起请求,那么每个组件都需要重复书写 this.$http.get('/users')
类似的代码,造成冗余
改进:对于每一个根路径,独立封装一个 request.js
模块,组件导入所需根路径对应的 axios
进行使用
import axios from 'axios'
const request = axios.create({ baseURL: 'http://api.com' }) export default request
|