0
0

More than 1 year has passed since last update.

JavaScript AJAX勉強

Last updated at Posted at 2022-01-22

メソッドの使い方などなかなか覚えられないので、アウトプットして定着させる目的で書きます。。。

Fetch

JavaScriptは必要な時にいつでもサーバーにリクエストを送れる。
- 入力データのSubmit
- ユーザーデータのロード
などが、ページをリロードしなくても可能になる。

JavaScriptからのリクエストはAJAX(Asynchronous JavaScript And XML)と呼ばれる。
歴史的な経緯からついた名前で、特にXMLを使う必要はない。

AJAXの方法の一つとしてfetch()メソッドがある。
基本的な構文は以下。

let promise = fetch(url, [options])
  • url : リクエストを送るURL
  • options : methodやheaderなど

fetch()はpromiseオブジェクトを返す。
サーバーからの応答を見るためthen()メソッドを使って、

Free fake APIでテスト。

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))
console
{
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
}

2行目のresponseはJavaScriptに組み込まれているResponseクラスのオブジェクト。
response.statusでHTTPリクエストのstatusを見ることができる。

この状態ではbodyの情報にはアクセスできないので、json()メソッドを使ってオブジェクトにする必要がある。
実際にjson()が返すのはpromiseオブジェクト。なので、then()を使ってチェーン状にすることができる。
なぜjson()がpromiseオブジェクトを返すのかというと、responseにはbodyの内容が含まれておらず、bodyの内容がロードされるまで待つ必要があるためらしい。
あまり理解できている自信がない・・・

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0