简体   繁体   English

Javascript:获取 api 与 AJAX

[英]Javascript : Fetch api vs AJAX

I have this code我有这个代码

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Is using Fetch API for a request like in the code above considered as an AJAX request?将 Fetch API 用于上述代码中的请求是否被视为 AJAX 请求?

I a request considered an AJAX request only if we use the XMLHttpRequest object ?仅当我们使用 XMLHttpRequest 对象时,我的请求才被视为 AJAX 请求?

是的,有几种方法可以发送异步请求,例如 jQuery、axios、Fetch API 或 XMLhttprequest。

fetch is an ajax request. fetch 是一个ajax请求。

but fetch is a simple api and have not, so I recommended fatcher但是 fetch 是一个简单的 api 并没有,所以我推荐fatcher

fatcher is a lightweight HTTP request library based on fetch , allows us to use native fetch for web requests in a browser and NodeJS environment. fatcher 是一个基于fetch的轻量级 HTTP 请求库,允许我们在浏览器和 NodeJS 环境中使用本机fetch进行 Web 请求。

It is wrapped using the native fetch , we require that browsers or NodeJS support fetch when we use it.它使用本机fetch包装,我们要求浏览器或 NodeJS 在使用时支持fetch

  • Fetch support is already pretty good in modern browsers, so we don't have to worry about FETCH compatibility现代浏览器对 Fetch 的支持已经相当不错了,所以我们不必担心 FETCH 的兼容性
  • In NodeJS, fetch already has some support starting with '18.0.0'在 NodeJS 中,从 '18.0.0' 开始的 fetch 已经有了一些支持

Fatcher aims to embrace the fetch of the standard library and at the same time provide some functions that cannot be provided in fetch , as well as make the function better expand and reuse. Fatcher 旨在拥抱标准库的fetch ,同时提供一些fetch无法提供的功能,并使功能更好地扩展和重用。

import { fatcher, isFatcherError } from 'fatcher';

fatcher({
    url: '/',
})
    .then(result => {
        // Response
        const { data, status } = result;
    })
    .catch(err => {
        // Catch Fatcher Error
        if (isFatcherError(err)) {
            // Request successfully. But response status code is not 2xx.
            console.error(err.toJSON());
            return;
        }

        // This is other errors.
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM