H5中的fetch和AJAX有什么区别
原创AJAX
$.ajax({
type: POST,
url: url,
data: data,
dataType: dataType,
success: function () {},
error: function () {}
});
传统AJAX指的是 XMLHttpRequest
,这是最早发送后端请求的技术。
fetch
try {
let response = await fetch(url);
let data = response.json();
console.log(data);
} catch(e) {
console.log("Oops, error", e);
}
fetch是基于Promise设计的, fetch不是AJAX进一步的封装,但原生的JS,未使用XMLHttpRequest对象。
fetch和AJAX主要区别是
1.fetch返回错误的http状态代码不会reject
fetch仅向网络请求报告错误,是400,500当请求成功时,服务器返回。 400,500 错误代码不 reject仅当网络错误导致请求未完成时,fetch 才会被 reject。
解决方案:
我们可以住在一楼。.then在内部手动引发异常,然后就可以使用它们了。.then .catch了。
fetch(
http://domain/service, {
method: GET
}
)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error(Network response was not ok.);
})
.then(json => console.log(json))
.catch(error => console.error(error:, error));
2.默认情况下,fetch不会携带cookie
解决方案:
添加配置项: fetch(url, {credentials: include})
3.fetch未设置超时
解决方案:
使用一个promise来概括一下,setTimeout()要设置时间,如果超过该事件,它将返回。reject
return new Promise((resolve, reject) => {
fetch(url, init)
.then(resolve)
.catch(reject);
setTimeout(reject, timeout);
})
}
在这里,fetch会和setTimeout同时,fetch是异步的,不会堵塞背部setTimeout的执行。
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
上一篇:Vue中父子组件的生命周期的执行顺序 下一篇:webpack的几种常用前端优化方案