1. XMLHttpRequest对象
现代浏览器,最开始与服务器交换数据,都是通过XMLHttpRequest对象。它可以使用JSON、XML、HTML和text文本等格式发送和接收数据。
优点:
- 不重新加载页面的情况下更新网页
缺点:
- 使用起来也
比较繁琐
,需要设置很多值 - 对于早期的IE浏览器,还需要
写兼容代码
if (window.XMLHttpRequest) { // model browser
xhr = new XMLHttpRequest()
} else if (window.ActiveXObject) { // IE 6 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
xhr.open("POST", url, true)
xhr.send(data)
xhr.onreadystatechange = function () {
try {
// TODO 处理响应
if (xhr.readyState === XMLHttpRequest.DONE) {
// XMLHttpRequest.DONE 对应值是 4
if (xhr.status === 200) {
// Perfect!
} else {
// There was a problem with the request.
}
} else {
// Not ready yet
}
} catch (e) {
// 通信错误的事件中(例如服务器宕机)
alert("Caught Exception: " + e.description)
}
}
2. jQuery ajax
为了更快捷的操作DOM,并且规避一些浏览器兼容问题,产生了jQuery。它里面的AJAX请求也兼容了各浏览器,可以有简单易用的方法. g e t , .get,.get,.post。简单点说,就是对XMLHttpRequest对象的封装
。
优点:
- 对原生XMLHttpRequest的封装,
做了兼容处理,简化了使用
。 - 增加了对
JSONP
的支持,可以简单处理部分跨域
。
缺点:
- 如果有多个请求,并且有依赖关系的话,
容易形成回调地狱
。 - 本身是针对MVC的编程,
不符合现在前端MVVM
的浪潮。 不独立
,ajax是jQuery中的一个方法。如果只是要使用ajax却要引入整个jQuery非常的不合理。
$.ajax({
type: "POST",
url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}
})
3. axios
Axios是本质也是对原生XMLHttpRequest的封装,只不过它是通过Promise方法来实现的
,可以用在浏览器和 node.js 中。
Vue2.0之后,尤雨溪大大推荐
大家使用axios来请求数据。
优点:
- 从浏览器中创建XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 支持拦截请求
- 支持取消请求
- 支持拦截响应
- 自动转换 JSON 数据
- 客户端支持防御 XSRF
缺点:
- 只持现代浏览器
axios({
method: "post",
url: "/user/12345",
data: {
firstName: "liu",
lastName: "weiqin"
}
})
.then(res => console.log(res))
.catch(err => console.log(err))
axios({
method: "post",
url: "/user/12345",
data: {//body参数 对应nodejs需要app.use(express.json()) 解析
firstName: "liu",
lastName: "weiqin"
},
params: {//query参数 对应nodejs需要app.use(express.urlencoded({ extended: true })) 解析
token
},
})
.then(res => console.log(res), err => console.log(err))
//async await方法
const res = await axios({ url: 'http://localhost:8080/api/login', method: 'post', data: user })
4. fetch
是什么
fetch是js 除了XMLHttpRequest之外的,另一种原生js网络请求获取数据的方式
。与XMLHttpRequest相比,fetch使用了Promise,这让它使用起来更加简洁,从而避免陷入”回调地狱”的情况。
fetch与ajax/XMLHttpRequest的不同
- fetch方法
返回的是一个promise对象
- fetch异步请求后,
返回的数据是一个stream对象,我们通过调用这个对象的json()方法,来读取返回数据,这个读取的过程是一个异步的,并且json方法最终会返回一个Promise对象,在其resolve回调中可以获取到请求到的数据。
同源请求
,fetch默认不会携带cookie- fetch不支持中断请求,不支持超时控制。
- fetch无法监测请求的进度,而XHR可以。
- fetch 目前不支持IE,如果你需要支持IE的话,你
需要使用polyfill库
。 - fetch 当服务器返回 400,500 错误码时,也会被当作resolve进行处理
仅当网络故障时或请求被阻止时,才会标记为 reject,
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
try {
//fetch得到的数据进行json转换后得到的是promise
const res = await (await fetch(url, { method: "GET", mode:'cros',})).json()
console.log(res)
//成功
if (res.code === 200) {
// console.log(res.daily);
return res.data[0].url
} else {
return ''
}
} catch (err) {
//失败
console.log('Fetch Error: ', err)
}