javascript
使用fetch封装ajax_如何使用Fetch在JavaScript中进行AJAX调用
使用fetch封裝ajax
I will be sharing bite sized learnings about JavaScript regularly in this series. We'll cover JS fundamentals, browsers, DOM, system design, domain architecture and frameworks.
在本系列中,我將定期分享有關(guān)JavaScript的小知識。 我們將介紹JS基礎(chǔ)知識,瀏覽器,DOM,系統(tǒng)設(shè)計,域架構(gòu)和框架。
Fetch is an interface for making an AJAX request in JavaScript. It is implemented widely by modern browsers and is used to call an API.
Fetch是用于在JavaScript中發(fā)出AJAX請求的接口。 它由現(xiàn)代瀏覽器廣泛實現(xiàn),并用于調(diào)用API。
const promise = fetch(url, [options])Calling fetch returns a promise, with a Response object. The promise is rejected if there is a network error, and it's resolved if there is no problem connecting to the server and the server responded a status code. This status code could be 200s, 400s or 500s.
調(diào)用fetch返回帶有響應(yīng)對象的Promise。 如果出現(xiàn)網(wǎng)絡(luò)錯誤,則將拒絕諾言;如果連接到服務(wù)器沒有問題,并且服務(wù)器響應(yīng)了狀態(tài)代碼,則可以解決諾言。 此狀態(tài)碼可以是200s,400s或500s。
A sample FETCH request -
樣本FETCH請求-
fetch(url).then(response => response.json()).catch(err => console.log(err))The request is sent as a GET by default. To send a POST / PATCH / DELETE / PUT you can use the method property as part of options parameter. Some other possible values options can take -
默認(rèn)情況下,該請求作為GET發(fā)送。 要發(fā)送POST / PATCH / DELETE / PUT,您可以將method屬性用作options參數(shù)的一部分。 其他一些可能的值options可以采用-
method: such as GET, POST, PATCH
method :例如GET,POST,PATCH
headers: Headers object
headers : headers頭對象
mode: such as cors, no-cors, same-origin
mode :例如cors , no-cors , same-origin
cache: cache mode for request
cache :請求的緩存模式
credentials
credentials
body
body
Check out the full list of available options here
在此處查看可用選項的完整列表
Example usage: This example demonstrates the usage of fetch to call an API and to get a list of git repositories.
用法示例:此示例演示fetch的用法,以調(diào)用API并獲取git存儲庫列表。
const url = 'https://api.github.com/users/shrutikapoor08/repos';fetch(url).then(response => response.json()).then(repos => {const reposList = repos.map(repo => repo.name);console.log(reposList);}) .catch(err => console.log(err))To send a POST request, here's how the method parameter can be used with async / await syntax.
要發(fā)送POST請求,以下是method參數(shù)與async / await語法一起使用的方式。
const params = {id: 123 }const response = await fetch('url', {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(params) });const data = await response.json();對更多JSBytes感興趣? 訂閱新聞通訊 (Interested in more JSBytes? Sign up for the newsletter)
翻譯自: https://www.freecodecamp.org/news/how-to-use-fetch-api/
使用fetch封裝ajax
總結(jié)
以上是生活随笔為你收集整理的使用fetch封装ajax_如何使用Fetch在JavaScript中进行AJAX调用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Box Shadow CSS教程–如何向
- 下一篇: Spring—注解开发