Fetch API 是什么?能代替 AJAX 吗?

短答案:

Fetch 是浏览器提供的原生 AJAX 接口。使用 window.fetch 函数可以代替以前的 $.ajax、$.get 和 $.post。

长答案:

前端发展地越来越快,我们用了好几年的 $.ajax,居然也渐渐变得过时了。

以前我们用 jQuery.ajax 发一个请求是这样的:

$.ajax('/').then(function(response){
    console.log(response)
})

现在我们用 fetch 发一个请求是这样的:

fetch('/').then(function(response){
    response.text().then(function(text){
        console.log(text)
    })
})

是不是感觉很像,像就对了,因为 Fetch API 就是浏览器提供的用来代替 jQuery.ajax 的工具。

AJAX 的原理

我们知道 jQuery.ajax 是使用 XMLHttpRequest 对象来发送异步请求的。

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      console.log(this.responseText);
    }
  };
  xhttp.open("GET", "/", true);
  xhttp.send();

是不是很麻烦,是不是?

正是由于 XMLHttpRequest 使用起来相当麻烦,所以大家才喜欢使用 jQuery 提供的 $.ajax 方法。

用 fetch 代替 $.ajax

随着 React.js、Angular.js 和 Vue.js 这些前端框架的流行,很多单页面应用已经不再使用 jQuery 了,这意味着你要自己对 XMLHttpRequest 进行封装,而很多人选择封装一个跟 jQuery.ajax 差不多的接口。

Fetch API 的出现,就是为了给类似的操作流程定一个接口规范。

换句话说,就是浏览器帮你把 jQuery.ajax 给实现了,以后大家都是用 fetch 来发送异步请求就好了。

Fetch API 提供的一组对象

window.fetch 函数只是 Fetch API 提供的众多接口中的一个,还有很多有用的对象:

  • window.Headers
  • window.Response
  • window.Request
  • ……

要学的东西又多了起来……

Fetch API 的特点

基于 Promise(如果你没有学过 Promise,强烈建议你学一学)
不需要依赖第三方库,就可以优雅地使用 AJAX
Fetch API 的问题

使用 fetch 无法取消一个请求。这是因为 Fetch API 基于 Promise,而 Promise 无法做到这一点。不过相信很快就会有对策。

兼容性

有的浏览器没有 Fetch API,没有关系,只要引入一个 polyfill 就可以了:GitHub – github/fetch: A window.fetch JavaScript polyfill.

作者:方应杭

31 thoughts on “Fetch API 是什么?能代替 AJAX 吗?”

  1. When someone writes an post he/she keeps the plan of a user in his/her brain that how a user can know it.

    Therefore that’s why this post is amazing. Thanks!

  2. Howdy just wanted to give you a brief heads up and let you
    know a few of the images aren’t loading properly.
    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different web browsers and both show the same outcome.

  3. My brother suggested I would possibly like this website.
    He was totally right. This publish truly made my day.
    You can not consider just how so much time I had spent for this
    info! Thank you!

  4. Good day! This is my 1st comment here so I just wanted
    to give a quick shout out and say I genuinely enjoy reading your blog posts.
    Can you suggest any other blogs/websites/forums that deal with
    the same topics? Thanks for your time!

  5. I am no longer positive the place you’re getting your information, however great topic.
    I must spend some time learning more or working out more.
    Thank you for excellent information I was on the lookout
    for this information for my mission.

  6. Hello there! I know this is somewhat off topic but I was wondering if you
    knew where I could find a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having problems finding one?
    Thanks a lot!

  7. When I initially commented I clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the identical comment. Is there any way you’ll be able to remove me from that service? Thanks!

  8. I simply had to appreciate you all over again. I do not know the things I would’ve undertaken without the actual pointers revealed by you relating to that subject matter. It absolutely was a fearsome setting for me personally, but taking a look at a specialised way you managed that took me to jump for delight. Now i’m grateful for your support as well as have high hopes you know what a powerful job you’re providing training other individuals through the use of your site. I am sure you have never met all of us.

  9. I’m also writing to make you understand what a magnificent discovery my friend’s daughter went through using your web site. She picked up numerous pieces, with the inclusion of what it’s like to have an ideal helping mood to make other folks without hassle understand a number of problematic issues. You undoubtedly exceeded visitors’ desires. Many thanks for displaying these effective, healthy, explanatory and in addition easy tips on this topic to Tanya.

  10. Thanks a lot for sharing this with all people you actually recognise what
    you are speaking approximately! Bookmarked. Please additionally discuss with my web site =).
    We will have a hyperlink exchange arrangement between us

  11. I intended to put you this very small note in order to say thank you over again for your personal marvelous concepts you’ve shared in this case. It has been so strangely open-handed with you giving without restraint all a few people might have sold as an e book in order to make some bucks for their own end, primarily since you could possibly have done it if you ever considered necessary. These guidelines also worked to be the easy way to be aware that most people have the identical eagerness much like mine to learn a little more in respect of this problem. I believe there are millions of more pleasant occasions up front for individuals that take a look at your website.

  12. I intended to draft you that very small word in order to say thank you as before for all the unique tips you have provided at this time. This has been simply open-handed with people like you to offer publicly just what a lot of folks would’ve distributed for an e-book to get some profit for themselves, most importantly seeing that you might have done it in case you desired. The strategies in addition acted as a good way to be aware that many people have the identical zeal similar to my very own to see way more in regard to this problem. I am certain there are many more pleasurable opportunities up front for people who start reading your blog.

  13. I must point out my respect for your kindness for visitors who absolutely need assistance with this particular topic. Your very own commitment to passing the solution all-around has been amazingly useful and has without exception made some individuals just like me to realize their aims. Your amazing important tips and hints denotes so much a person like me and even more to my colleagues. Best wishes; from each one of us.

  14. I am also commenting to let you understand of the fantastic encounter my friend’s daughter gained checking your blog. She discovered so many things, most notably how it is like to possess a marvelous giving heart to make many more without problems comprehend several problematic subject areas. You truly did more than people’s expected results. Thanks for churning out such good, safe, explanatory and even easy tips on the topic to Janet.

  15. I truly wanted to write a comment to be able to say thanks to you for those unique concepts you are showing at this site. My rather long internet look up has now been honored with beneficial information to write about with my friends. I would mention that most of us website visitors are very much endowed to be in a wonderful network with many marvellous people with very beneficial pointers. I feel really grateful to have come across your website page and look forward to tons of more excellent times reading here. Thanks once more for all the details.

  16. I definitely wanted to jot down a quick comment to be able to express gratitude to you for some of the awesome instructions you are sharing at this website. My rather long internet lookup has now been honored with reasonable knowledge to exchange with my guests. I ‘d tell you that many of us readers are undoubtedly fortunate to dwell in a decent community with so many lovely professionals with helpful tips and hints. I feel very much grateful to have encountered the website and look forward to so many more thrilling times reading here. Thank you once again for all the details.

  17. fantastic publish, very informative. I ponder why the other experts of this sector do not realize this.
    You should proceed your writing. I’m sure, you’ve a great readers’ base already!

  18. I together with my guys have been digesting the good tips and hints located on your web blog and so instantly developed a terrible feeling I had not thanked the site owner for those tips. These ladies are already totally joyful to read through all of them and have in effect really been taking advantage of them. We appreciate you really being so kind as well as for using varieties of marvelous areas most people are really desirous to understand about. Our honest apologies for not saying thanks to sooner.

  19. Oh my goodness! Impressive article dude! Thank you so much, However I am having issues with your RSS.
    I don’t know the reason why I cannot join it. Is there anybody else getting identical RSS issues?
    Anyone who knows the answer can you kindly respond? Thanks!!

  20. I simply wanted to compose a word in order to express gratitude to you for those marvelous concepts you are sharing at this website. My considerable internet lookup has finally been compensated with extremely good knowledge to write about with my family and friends. I ‘d express that we website visitors are very blessed to be in a notable community with many perfect individuals with very helpful guidelines. I feel extremely happy to have come across the website page and look forward to really more brilliant moments reading here. Thanks once again for a lot of things.

  21. I precisely wished to thank you very much again. I do not know the things that I would’ve worked on in the absence of the basics shared by you on such a problem. It was before an absolute alarming matter in my circumstances, however , discovering your specialised style you managed that forced me to cry over gladness. I will be grateful for this work and wish you recognize what a powerful job you were undertaking training others with the aid of your web page. I am certain you’ve never met any of us.

  22. You made some first rate points there. I appeared on the internet for the difficulty and found most people will associate with along with your website.

  23. A powerful share, I simply given this onto a colleague who was doing a little analysis on this. And he in actual fact bought me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to debate this, I feel strongly about it and love reading more on this topic. If possible, as you grow to be experience, would you mind updating your weblog with more details? It is highly helpful for me. Massive thumb up for this weblog publish!

发表评论

电子邮件地址不会被公开。